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 CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by