开发者

How match all possible numbers in a javascript expression?

I've seen a lot of regex's matching numbers but none of them quite capture all valid numbers.

For example, I need to match all of the following:

//All of these can be preceded/followed by any of: +=-()!~%$#^&*{}[]|\;<>,
23
-23
4.8
1.3e-8
1.38e+5
-1.3e-2
-1.4e+2

but NOT match the following:

w23
-23w
_4.8 //This would see 8 as a number but not _4.
4yes
1.3ed-8 //This would see 1 and -8开发者_Python百科 as numbers but not .3ed
12dog
12foo

Is there a way to do such a regex?


I find your requirements a bit bizarre, but this regex does what you want for all your examples:

-?\b\d+(\.\d+)?([eE][-+]?\d+)?\b

The key to making it fit your specification is to use the \b word boundary match.

Results for each:

23:
  23
-23:
  -23
4.8:
  4.8
1.3e-8:
  1.3e-8
1.38e+5:
  1.38e+5
-1.3e-2:
  -1.3e-2
-1.4e+2:
  -1.4e+2
w23:
-23w:
_4.8:
  8
4yes:
1.3ed-8:
  1
  -8
12dog:
12foo:


If you use the following regex with the m flag (^ and $ match the beginning and end of each new line), it will return valid for all of your supplied valid numbers, and invalid for the supplied invalid numbers:

^[+=\-()!~%$#\^&*{}[\]|\\;<>,]*\d+[\.\d]*([a-zA-Z][\+\-]\d+)?[+=\-()!~%$#\^&*{}[\]|\\;<>,]*$

Broken down:

^                                   #start of string (line, with "m" flag)
  [+=\-()!~%$#\^&*{}[\]|\\;<>,]*    #zero or more of any of these characters.
  \d+                               #one or more digits (basic number: 123)
  [\.\d]*                           #zero or more periods or digits (to account for floats: 1.11)
  ([a-zA-Z][\+\-]\d+)?              #one or zero instance of a letter, a + or - sign, then 1 or more digits (to account for scientific notation floats: 1.23e+3 or 1.23e-3)
  [+=\-()!~%$#\^&*{}[\]|\\;<>,]*    #once again, zero or more of any of these characters.
$                                   #end of string (line, with "m" flag)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜