regular expression for this

1 view
Skip to first unread message

aaragon

unread,
Nov 23, 2009, 9:54:38 PM11/23/09
to Regex
Hi guys,

I'm new to this group and I joined after spending quite a while trying
to get a regular expression. The line I'm trying to read from a file
looks like the following:

1, 0.000000e+00, 1.000000e+00, 2.000000e+00

So the first item is a digit, followed by 3 floats. I tried the
following regular expression:

\s*(\d+)(?:\s*,?\s*(\d+.?\d*[eE][+-]\d+)){1,3}

and the problem is that I obtain only 2 groups (instead of 4).

Can someone point out what is the problem here? Also, is there a
better way to obtain a regular expression for a float?

aa

eugeny....@gmail.com

unread,
Nov 24, 2009, 5:18:29 AM11/24/09
to Regex
I don't see big faults in your expression except may be not escaping
the dot.
Having tested your expression I see it catches the whole line.

I might improved it a bit this way
^\s*\d+((,\s+[+-]?\d*\.?\d+[eE][+-]\d+)+)\s*$

If you know there will be always not less than 1 and not more than 3
floats
in a line and if you want each of them to be stored into a separate
backreference,
the (,\s+[+-]?\d*\.?\d+[eE][+-]\d+) part should be repeated personally
for each floating point number. This way (in a free spacing mode):


^\s*(\d+)
(?:,\s+([+-]?\d*\.?\d+[eE][+-]\d+)) #1st float $2
(?:,\s+([+-]?\d*\.?\d+[eE][+-]\d+))? #2nd float $3
(?:,\s+([+-]?\d*\.?\d+[eE][+-]\d+))? #3rd float $4
\s*$

--
Regards
Eugeny
Reply all
Reply to author
Forward
0 new messages