I am having trouble with finding a good regular expression

G

greenflame

I am trying to find a regular expression that returns true in the
following cases but no others.

2.0
2.4
2.
324.0e345
234e34
34.e-43
234.673
-2.0
-2.4
-2.
-324.0e345
-234e34
-34.e-43
-234.673

In other words I am looking for a regular expression that returns true
only if there is a decimal in it. It can allow negative numbers. It can
have as many digits before and after the decimal. It can also allow
scientific notation with either the e or E. I have done some looking
around and found some but they returned false in some of the cases and
returned true for some of the cases I did not want them to. Please help.
 
W

web.dev

greenflame said:
I am trying to find a regular expression that returns true in the
following cases but no others.
[snip]
[snip]
-234e34

The above two cases should return false. Why? Because of your comment
below:
In other words I am looking for a regular expression that returns true
only if there is a decimal in it.

This is the regular expression I've made. It appears to pass the test
cases (with the exception of above two), and the description of what
you're looking for.

var re = /^-?\d+\.\d*((e|E)-?\d+)?$/i;

If this expression does not work for you, could you post for which
values the expression does not pass? Then I can help you adjust
accordingly.

Hope this helps. :)
 
S

Stephen Chalmers

greenflame said:
I am trying to find a regular expression that returns true in the
following cases but no others.

2.0
2.4
2.
324.0e345
234e34
34.e-43
234.673
-2.0
-2.4
-2.
-324.0e345
-234e34
-34.e-43
-234.673

In other words I am looking for a regular expression that returns true
only if there is a decimal in it. It can allow negative numbers. It can
have as many digits before and after the decimal. It can also allow
scientific notation with either the e or E. I have done some looking
around and found some but they returned false in some of the cases and
returned true for some of the cases I did not want them to. Please help.

In addition to your specified formats (those with a decimal point), this expression will allow .2 and exponential
notation may include a '+' sign.

/^-?((\d+\.)|(\.\d))\d*(e(-|\+)?\d+)?$/i
 
G

greenflame

Ok. Thanks those look good. I will do some testing on them. Thanks.
This helps a lot.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top