【问题标题】:Max length ignoring one character in Regex忽略正则表达式中的一个字符的最大长度
【发布时间】:2019-10-24 06:37:35
【问题描述】:

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

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

我还想设置最大长度条件,以便用户只能输入 12 位数字,最大长度应排除“。”我如何使用正则表达式来做到这一点。

【问题讨论】:

  • 轻松获胜:创建两个正则表达式,一个用于 12 检查,一个用于您已经拥有的,两者必须匹配。
  • 好主意,但你会怎么做呢?例如 ^[0-9\.]{13}$ 不好,因为它允许多个点。 @MartinWickman
  • 假设你有一种编程语言:if (regex1.match(input) && match(regex2.match(input)) { ...}
  • 谢谢大家。我在 JQuery 中使用它作为输入过滤器,所以我需要在正则表达式中使用它以保持简单。

标签: regex regex-lookarounds regex-group regex-greedy


【解决方案1】:

您可以使用正向前瞻来检查带有最多 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

【讨论】:

【解决方案2】:

我们可以尝试使用负前瞻:

^(?:(?!.*\.)(?!\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

【讨论】:

    【解决方案3】:

    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

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多