2

如何创建带小数点分隔符的数字正则表达式,但也限制长度

我创建了这个:

^[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

提前致谢

4

2 回答 2

4
^(?:\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

请注意(如在您的示例中).123123.无效。

于 2013-02-20T22:22:33.650 回答
1

如果您不使用正则表达式来计算长度,它会更清晰甚至更快。测试它^\d+(?:\.\d+)$,删除点并取长度。

如果你真的需要它是一个正则表达式,你可以使用前瞻来分别检查格式长度:

^\d{1,10}$|^(?=.{11}$)\d+\.\d+$

解释:

^          # At the start of the string
(?:        # either
 \d{1,10}  # up to 10 digits
|          # or
 (?=       # from here
  .{11}    # 11 characters
  $        # to the end
 )         # and as well
 \d+\.\d+  # two dot-separated digit sequences
)          # 
$          # 
于 2013-02-20T22:27:07.753 回答