我如何创建带有小数点分隔符的数字正则表达式,同时限制长度
我创建了这个:
^[0-9]([0-9]*[.]?[0-9]){1,10}$
那么 1234567890.1234567890 是有效的,但是使用了 20(+1 -> 小数分隔符)个字符。
如何限制为 10 个字符?
有效:
1234567890
123456789.0
12345678.90
1234567.890
123456.7890
12345.67890
12345.67890
1234.567890
123.4567890
12.34567890
1.234567890
无效:
12345678901
12345678901.
123456789.01
12345678.901
1234567.8901
123456.78901
12345.678901
12345.678901
1234.5678901
123.45678901
12.345678901
1.2345678901
.12345678901
提前致谢
最佳答案
^(?:\d{1,10}|(?!.{12})\d+\.\d+)$
解释:
^ # Start of string
(?: # Either match...
\d{1,10} # an integer (up to 10 digits)
| # or
(?!.{12}) # (as long as the length is not 12 characters or more)
\d+\.\d+ # a floating point number
) # End of alternation
$ # End of string
请注意(如您的示例所示).123
或 123.
无效。
关于带长度的 RegEx 数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990962/