Help with Regexp

5 次查看(过去 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 CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by