regexp to match certain words in a string

I have a string which looks like this
ternaryMassDensity{Xmole(1)=0.0Xmole(2)=1.0rho(1)=2343rho(2)=2343}ThermalConductivity{Xmole(1)=0.0Xmole(2)=1.0kappa(1)=3,2,13,...,2kappa(2)=2,1,11,...,3Tref=...}ElectricalConductivity{sigma0=1e5Tref=300}Mobility{Xmole(1)
I need to match the words like MassDensity, Mobility, ThermalConductivity etc.,
Can anyone tell me how I can do this using regexp, or any other way which might be easier.

 採用された回答

Jacob Halbrooks
Jacob Halbrooks 2014 年 2 月 26 日

0 投票

Looking at your string, I see parameter value pairs in the pattern of Param{Value}Param{Value}. If that is the case, then a regular expression can pull these out using the code below (note that I added a closing curly bracket to your string):
>> pvRawString = 'ternaryMassDensity{Xmole(1)=0.0Xmole(2)=1.0rho(1)=2343rho(2)=2343}ThermalConductivity{Xmole(1)=0.0Xmole(2)=1.0kappa(1)=3,2,13,...,2kappa(2)=2,1,11,...,3Tref=...}ElectricalConductivity{sigma0=1e5Tref=300}Mobility{Xmole(1)}';
>> pvs = regexp(pvRawString, '(?<Parameter>\w+){(?<Value>.*?)}','names');
>> pvs(1)
ans =
Parameter: 'ternaryMassDensity'
Value: 'Xmole(1)=0.0Xmole(2)=1.0rho(1)=2343rho(2)=2343'
The "pvs" variable above is a struct array of length 4, one for each parameter/value pair found. Note that the regular expression above will fail if curly brackets are nested within the parameter value.

3 件のコメント

Ajay
Ajay 2014 年 2 月 26 日
actually I tried but it returns a 12x1struct with each cell containing items like 1x1struct.
Ajay
Ajay 2014 年 2 月 26 日
actually you have the exact idea.
Ajay
Ajay 2014 年 2 月 26 日
actually I found what I was looking for thanks for your help. Really appreciated.

サインインしてコメントする。

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2014 年 2 月 26 日

1 投票

Here is how:
WORDS = {'MassDensity', 'Mobility', 'ThermalConductivity'}
IDX = regexp(str, WORDS)
% IDX{k} holds all the start indices for the word WORDS{k}
But what is the next step?

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

タグ

質問済み:

2014 年 2 月 26 日

コメント済み:

2014 年 2 月 26 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by