【问题标题】:Combine 2 conditions in regex在正则表达式中结合 2 个条件
【发布时间】:2021-02-14 20:44:16
【问题描述】:

我想创建一个正则表达式来检查非 ASCII 字符和一些特殊字符。

 /^[\x00-\x7F]+$/  

 '[^{}$]*'

这些条件是单独工作的,但当我将它们结合起来时就不行了。尝试过

/^([\x00-\x7F]|[^{}$]*)$/   but failing.

任何帮助将不胜感激。提前致谢。

【问题讨论】:

  • 你在组合的第一部分缺少+/^([\x00-\x7F]+|[^{}$]*)$/
  • 扩展第一个备用组以包含特殊字符
  • 如何扩展它?
  • 请添加一些有效和无效匹配的示例

标签: javascript java regex string match


【解决方案1】:

您的正则表达式的 [\x00-\x7F] 部分似乎有问题。我已经尝试了以下方法并且它有效。

^([[:ascii:]]+$|[^{}$]*)$

【讨论】:

    【解决方案2】:

    ^[\x00-\x7F]+$ - 匹配一个完全由 ASCII 字符组成的字符串。

    [^{}$]* 匹配零个或多个不同于{}$ 的字符。

    所以,第二条规则匹配任何字符串。如果这是您的意图,只需使用第一个正则表达式。

    如果您想匹配任何纯 ASCII 字符串,不包括 {}$ 使用

    ^(?=[\x00-\x7F]+$)[^{}$]*$
    

    proof

    说明

    --------------------------------------------------------------------------------
      ^                        the beginning of the string
    --------------------------------------------------------------------------------
      (?=                      look ahead to see if there is:
    --------------------------------------------------------------------------------
        [\x00-\x7F]+             any character of: '\x00' to '\x7F' (1 or
                                 more times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
        $                        before an optional \n, and the end of
                                 the string
    --------------------------------------------------------------------------------
      )                        end of look-ahead
    --------------------------------------------------------------------------------
      [^{}$]*                  any character except: '{', '}', '$' (0 or
                               more times (matching the most amount
                               possible))
    --------------------------------------------------------------------------------
      $                        before an optional \n, and the end of the
                               string
    

    【讨论】:

      猜你喜欢
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 2018-07-04
      • 2016-07-30
      相关资源
      最近更新 更多