Regular expression does not match a number with e+ or e-
I want to match any number w开发者_开发百科ith a regular expression. I have written this expression (added whitespace for readability):
( ([0-9]+(\.[0-9]*)?) | (\.[0-9]+) )( (e|E)(\+|\-)[0-9](\.[0-9])? )?
This would need to match any number in one of the following forms:
12345
12.345
.12345
12345.
12e-345
or12E-345
12e+345
or12E+345
It matches the first four notations, but the last four (those with e- and e+) don't. What have I done wrong? Thanks in advance.
Focus on that part of the expression:
(e|E)(\+|\-)[0-9](\.[0-9])?
You're only allowing one digit after e|E
, optionally followed by a .
and one other digit.
Maybe it is the final slashdot '\.'.
Also, there is no * so it will only allow one or two digits in the exponent.
(\.[0-9])? )?
You're looking for 1 digit after the [eE]. Change the ? to a +
( ([0-9]+(\.[0-9]*)?) | (\.[0-9]+) )( (e|E)(\+|\-)[0-9]+(\.[0-9])+ )?
Because the regex matches numbers of the form 12.34e+4.5
. The [0-9](\.[0-9])?
part should be changed to [0-9]+
.
( ([0-9]+(\.[0-9]*)?) | (\.[0-9]+) )( (e|E)(\+|\-)[0-9]+ )?
See also How to detect a floating point number using a regular expression.
Use this: \d+[eE][+-]\d+|\d+\.?\d*|\.\d+
精彩评论