简体   繁体   中英

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."

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

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

See this demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM