Filter löschen
Filter löschen

Help with Regexp

4 Ansichten (letzte 30 Tage)
Edward
Edward am 20 Apr. 2012
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 Kommentare
Edward
Edward am 20 Apr. 2012
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 am 20 Apr. 2012
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.)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 20 Apr. 2012
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 Kommentare
Edward
Edward am 20 Apr. 2012
That command returns a 0x0 array for numdata, what am i doing wrong?
Walter Roberson
Walter Roberson am 20 Apr. 2012
Sorry, \ was in wrong place. I have edited the expression.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by