例子:
"1" yes
"-1" yes
"- 3" no
"1.2" yes
"1.2.3" no
"7e4" no (though in some cases you may want to allow scientific notation)
".123" yes
"123." yes
"." no
"-.5" yes
"007" yes
"00" yes
这允许在前面添加可选的“+”和“-”。并允许尾随或初始空格。
/^\s*[+-]?(?:\d+\.?\d*|\d*\.\d+)\s*$/
有几种选择。首先,使用零宽度的先行断言可以使正则表达式的其余部分更简单:
/^[-+]?(?=\.?\d)\d*(?:\.\d*)?$/
如果您想避免前瞻,那么我会尝试阻止正则表达式回溯:
/^[-+]?(?:\.\d+|\d+(?:\.\d*)?)$/
/^[-+]?(\.\d+|\d+(\.\d*)?)$/ # if you don't mind capturing parens
请注意,您说的是“以 10 为底”,因此您实际上可能希望禁止额外的前导零,因为“014”可能意味着八进制:
/^[-+]?(?:\.\d+|(?:0|[1-9]\d*)(?:\.\d*)?)$/
/^[-+]?(\.\d+|(0|[1-9]\d*)(\.\d*)?)$/
最后,您可能需要替换\d为,[0-9]因为某些正则表达式不支持\d,或者因为某些正则表达式允许\d匹配 0..9 以外的 Unicode“数字”,例如“ARABIC-INDIC DIGIT”。
/^[-+]?(?:\.[0-9]+|(?:0|[1-9][0-9]*)(?:\.[0-9]*)?)$/
/^[-+]?(\.[0-9]+|(0|[1-9][0-9]*)(\.[0-9]*)?)$/
The regular expression in perlfaq4: How do I determine whether a scalar is a number/whole/integer/float? does what you want, and it handles the "e" notation too.
while( <DATA> )
{
chomp;
print /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/ ?
"$_ Works\n"
:
"$_ Fails\n"
;
}
__DATA__
1
-1
- 3
1.2
1.2.3
7e4
.123
123.
.
-.5
匹配所有指定的示例,不捕获任何组:
^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$
不匹配“1”。(ETC):
^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$
不打扰空格(使用修剪功能)。
根据您在此功能中编码的语言,可能已经存在。