【问题标题】:Regex to allow only negative number in decimals and 0正则表达式只允许小数和 0 中的负数
【发布时间】:2020-12-20 03:13:04
【问题描述】:

需要一个只允许 0 和负数的正则表达式。下面的表达式也允许正数。

^-?[0-9]\d*(\.\d+)?$

【问题讨论】:

    标签: regex regex-group regexp-replace


    【解决方案1】:

    我会在这里使用替代:

    ^(?:0(?:\.0+)?|-\d+(?:\.\d+)?)$
    

    Demo

    ^(?:                from the start of the input
        0(?:\.0+)?      match 0, or 0.0, 0.00 etc.
        |               OR
        -\d+(?:\.\d+)?  match a negative number, with optional decimal component
    )$                  end of the input
    

    【讨论】:

    • 这匹配 '0' 中的 '00cat'。正如您将立即看到的那样,问题在于锚点^ 仅适用于交替的第一部分,而$ 仅适用于交替的最后部分。拍脑袋,嗯?
    • 不,一点也不。
    【解决方案2】:

    我建议你用正则表达式匹配

    r'^(?:0|-(?:0\.\d+|[1-9]\d*(?:\.\d+)?))$'
    

    Start your engine!

    这匹配:'0''-0.123'-0.000'0.123'-17'-29.33'-29.00'

    不匹配:'00''-017''12''44.7'

    Python 的正则表达式引擎执行以下操作。

    ^                : match beginning of string
    (?:              : begin non-capture group
      0              : match '0'
      |              : or
      -              : match '-'
        (?:          : begin a non-capture group
          0\.\d+     : match '0.' then 
          |          : or
          [1-9]\d*   : match a digit other than zero then 0+ digits
          (?:\.\d+)  : match '.' then 1+ digits in a non-capture group
          ?          : make the non-capture group optional
        )            : end non-capture group
    )                : end non-capture group
    $                : match end of string
    

    【讨论】:

    • @Tim,你一定是在开玩笑。当我发布时,我的答案肯定与您的不同,因为您的答案不正确。此外,您的正则表达式仍然匹配 '00''-017',而我的则不匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    相关资源
    最近更新 更多