ben432rew
ben432rew

Reputation: 1902

What is wrong with my Regex and why?

The following regex:

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

incorrectly accepts 1+1 and 1f5 which aren't real JavasScript numbers.

I am attempting to make a regex that "matches only JavaScript-style numbers. It must support an optional minus or plus sign in front of the number, the decimal dot, and exponent notation—5e-3 or 1E10— again with an optional sign in front of the exponent. Also note that it is not necessary for there to be digits in front of or after the dot, but the number cannot be a dot alone. That is, .5 and 5. are valid JavaScript numbers, but a lone dot isn’t."

Upvotes: 1

Views: 84

Answers (2)

vks
vks

Reputation: 67988

You need to escape the .'s in your regex by \. Also, you need to escape all + in your regex by \.

See this demo.

Upvotes: 2

adam0101
adam0101

Reputation: 31115

You left one of your . unescaped. Make sure all have a backslash before it.

Upvotes: 3

Related Questions