最大长度忽略正则表达式中的一个字符

Max length ignoring one character in Regex

我有一个正则表达式,最多允许 6 位小数(“.”是小数点分隔符)

/^\d*[.]?\d{0,6}$/

我还想设置最大长度条件,以便用户只能输入 12 位数字并且最大长度应排除“.”。我如何使用 Regex 做到这一点。

我们可以尝试使用否定前瞻:

^(?:(?!.*\.)(?!\d{13})|(?=.*\.)(?![0-9.]{14}))\d+(?:\.\d{1,6})?$

Demo

下面是对正则表达式的解释:

^(?:                        from the start of the string
    (?!.*\.)(?!\d{13})      assert that no more than 12 digits appear
                            (in the case of a number with NO decimal point)
    |                       or
    (?=.*\.)(?![0-9.]{14})) assert that no more than 13 digits/decimal point appears
                            (in the case of a number which HAS a decimal point)
    \d+                     then match one or more digits (whole number portion)
    (?:\.\d{1,6})?          followed by an optional decimal component (1 to 6 digits)
$                           end of the string

您可以使用正向先行检查小数点后最多 6 位数字或 12 位数字的字符串)然后匹配最多 13 个字符:

^(?=\d*\.\d{0,6}$|\d{1,12}$).{1,13}$

对于此输入,第 2 个和第 5 个值将匹配:

1234567890123
123456.789012
12345.6789012
1234567.890123
12345.67890

Demo on regex101

TL;DR;

^(?!(?:\D*\d){13})\d*[.]?\d{0,6}$ 
^(?=(?:\D*\d){0,12}\D*$)\d*[.]?\d{0,6}$

您可以使用一种简单的积极前瞻方法:保留您的模式(如果它按您预期的那样工作)并插入

(?=(?:\D*\d){0,x}\D*$)

^ 之后,将 x 更改为所需的位数。

因此,您可以使用

^(?=(?:\D*\d){0,12}\D*$)\d*[.]?\d{0,6}$
 ^^^^^^^^^^^^^^^^^^^^^^^

(?=(?:\D*\d){0,12}\D*$) 匹配一个位置,该位置紧跟 0 到 12 次出现的任何 0+ 非数字字符,后跟一个数字 1,然后是任何 0+ 非数字到末尾字符串.

regex demo

或者,禁止超过 13 位的字符串:

^(?!(?:\D*\d){13})\d*[.]?\d{0,6}$
 ^^^^^^^^^^^^^^^^^

(?!(?:\D*\d){13}) 是一个否定前瞻,如果出现 13 次任何 0+ 非数字后跟单个数字字符,则匹配失败。

当您需要允许空字符串时,这比积极的先行方法要好。

regex demo