我见过很多正则表达式的匹配数字,但没有一个能完全捕获所有有效数字。
例如,我需要匹配以下所有内容:
//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
但不匹配以下内容:
w23
-23w
_4.8 //This would see 8 as a number but not _4.
4yes
1.3ed-8 //This would see 1 and -8 as numbers but not .3ed
12dog
12foo
有没有办法做这样的正则表达式?
最佳答案
我发现您的要求有点奇怪,但是这个正则表达式可以满足您对所有示例的要求:
-?\b\d+(\.\d+)?([eE][-+]?\d+)?\b
使其符合您的规范的关键是使用 \b
字边界匹配。
每个结果:
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:
关于javascript - 如何匹配 javascript 表达式中所有可能的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919737/