Read a string with numbers and scientific notations

Dear All,
I am trying to read a text file looks like this:
# Counters
sec=60, Monitor=8.66289e+06, bstop=818664, I0=829726, I1=0, ch5=0, ch6=0, ch7=0.
I would like to read the Monitor value (8.66289e+06). I was using
k=sprintf('txt_files/MnO2_20170512_05120943_%04d.txt',i);
filetext=fileread(k);
numbers = str2double(regexp(filetext, '(?<=Monitor=[^0-9]*)[0-9]*\.?[0-9]+', 'match'));
In this way I can get the number "8.66289". But today I would like to include the scientific notation as well. So my output will be "8.66289e+06". I am not really sure how to proceed with this even though I searched in the forum.
I tried
numbers3 = regexp(filetext, '(?<== )((\d|(+)|(\.)|(e))+','match');
and
numbers3=sscanf(sprintf('%s ',numbers3{:}),'%g')
But looks like something was not right in my code.
Thank you for help!

 採用された回答

Walter Roberson
Walter Roberson 2017 年 7 月 4 日

0 投票

S = 'sec=60, Monitor=8.66289e+06, bstop=818664, I0=829726, I1=0, ch5=0, ch6=0, ch7=0.';
result = regexp(S, '(?<name>\w+)=(?<value>[^,]+)', 'names');
>> result(2)
ans =
struct with fields:
name: 'Monitor'
value: '8.66289e+06'

3 件のコメント

BRC
BRC 2017 年 7 月 4 日
Thank you very much for answering my question! It worked out perfectly. A follow-up question though...could you let me know how to pull out the 8.66289e+06 and save it to an array? I have 1000 files but I am not familiar with structure files. Thanks!!
BRC
BRC 2017 年 7 月 4 日
I tried
numbers= regexp(filetext, '(?<name>\w+)=(?<value>[^,]+)', 'names');
a=numbers(2);
c = struct2cell(a);
m(i)=c(2)
but the error message was
The following error occurred converting from cell
to double:
Error using double
Conversion to double from cell is not possible.
Walter Roberson
Walter Roberson 2017 年 7 月 4 日
all_values_as_numeric = str2double( {result.value} );
Note: if you can count on the order being the same each time, then
S = 'sec=60, Monitor=8.66289e+06, bstop=818664, I0=829726, I1=0, ch5=0, ch6=0, ch7=0.';
result = regexp(S, '(?<==)([^,]+)', 'match');
all_values_as_numeric = str2double(result);

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

その他の回答 (0 件)

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by