Help with Regexp

2 ビュー (過去 30 日間)
Edward
Edward 2012 年 4 月 20 日
So i have a table of numbers read in using fread from a .dat file:
0 0 3.51563 50 35.1563
0.094 10 3.47656 50 34.7656
Including some decimals and some integers, I've tried using:
numdata=regexp(data,'(-)*(\d+.)*(\d+)','match');
to get each of these numbers into an individual element of array numdata but for some reason regexp reads in the whole line of numbers into one element rather than each one individually. Thanks for any help
  2 件のコメント
Edward
Edward 2012 年 4 月 20 日
for example if i output numdata i get:
'0 0 3.51563 50 35.1563'
for element 1 when really i want numdata(1)=0, numdata(3)=3.51563 etc
Walter Roberson
Walter Roberson 2012 年 4 月 20 日
You won't be able to get that from regexp. You will be able to get numdata{1} = '0', numdata{3} = '3.51563' and so on, and you will be able to use str2double() to convert the values to numeric. However, if you were going to use str2double() to convert the values to numeric then you might as well let str2double() do almost all the pattern recognition, just using regexp() to 'split' on whitespace (because str2double will only process one number per string.)

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

採用された回答

Walter Roberson
Walter Roberson 2012 年 4 月 20 日
The dot matches everything. You need \. to match a period.
numdata = regexp(data, '-?\d+(\.\d+)?', 'match');
This assumes that if the decimal point is present then it is always followed by at least one digit, and it assumes that there is always at least one digit before the decimal point. In particular,
17.
and
.3579
are examples of numeric formats that the expression would not match.
The expression always will not match numbers in exponential format.
  2 件のコメント
Edward
Edward 2012 年 4 月 20 日
That command returns a 0x0 array for numdata, what am i doing wrong?
Walter Roberson
Walter Roberson 2012 年 4 月 20 日
Sorry, \ was in wrong place. I have edited the expression.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by