Javascript正则表达式,用于检查字符串是否为有效数字

Javascript regex to check if string is a valid number

本文关键字:是否 有效数字 字符串 检查 正则表达式 用于 Javascript      更新时间:2024-01-20

我希望这个Regex与这些有效的数字格式匹配:

"^[+,-]?[0-9]*(''.[0-9]*)?$"
1. [+,-]? : + or - optional
2. [0-9]* : as many 0 to 9 number
3. (''.[0-9]*)? : . and as many 0 to 9 number optional

我差不多到了,因为我得到了如下所需:

"99999"  -> true
"99"     -> true
"9.9"    -> true
"9.999"  -> true
"9."     -> true
"-9."    -> true
"+9.9"   -> true
"-0.9"   -> true
"-.9"    -> true

但是,以下情况应该为false,但Regex输出true:

"+."      
"."

我需要更改什么?

您可以使用以下正则表达式:

/^[+-]?(?:'d+'.?|'d*'.'d+)$/

RegEx演示

您可以在开始时添加一个负前瞻。

^(?![+-]?'.$)[+-]?'d*(?:'.'d*)?$

演示

^(?!(?:'+|'+'.|'.)$)[+,-]?[0-9]*('.[0-9]*)?$

试试这个。请参阅演示。

https://regex101.com/r/oL9kE8/3

escape ' if required

^(?!(?:''+|''+''.|''.)$)[+,-]?[0-9]*(''.[0-9]*)?$

negative lookahead将确保+.+.不匹配。