【问题标题】:Match words that consist of specific characters, excluding between special brackets匹配由特定字符组成的单词,不包括特殊括号之间
【发布时间】:2021-01-02 21:08:58
【问题描述】:

我正在尝试匹配仅包含此字符类中的字符的单词[A-z'\\/%]排除以下情况:

  • 它们介于<> 之间
  • 它们在[] 之间
  • 它们在{} 之间

所以,假设我有这个有趣的字符串:

[beginning]<start>How's {the} /weather (\\today%?)[end]

我需要匹配以下字符串:

[ "How's", "/weather", "\\today%" ]

我尝试过使用这种模式:

/[A-z'/\\%]*(?![^{]*})(?![^\[]*\])(?![^<]*>)/gm

但由于某种原因,它匹配:

[ "[beginning]", "", "How's", "", "", "", "/weather", "", "", "\\today%", "", "", "[end]", "" ]

我不确定为什么我的模式允许 [] 之间的内容,因为我使用了 (?![^\[]*\]),并且类似的方法似乎适用于 not 匹配 {these cases}&lt;these cases&gt;。我也不确定为什么它匹配所有的空字符串。

有什么智慧吗? :)

【问题讨论】:

    标签: javascript regex string match


    【解决方案1】:

    您的模式本质上存在两个问题:

    1. 如果您打算只匹配字母,切勿在字符类中使用A-z(因为它不仅匹配字母1)。请改用a-zA-Z(或A-Za-z)。

    2. 在字符类之后使用* 量词将允许空匹配。请改用+ 量词。

    所以,固定模式应该是:

    [A-Za-z'/\\%]+(?![^{]*})(?![^\[]*\])(?![^<]*>)
    

    Demo.


    1[A-z] 字符类的意思是“匹配任何 ASCII 码在 65 到 122 之间的字符”。问题在于 91 到 95 之间的代码不是 字母(这就是原始模式匹配 '[' 和 ']' 等字符的原因)。

    【讨论】:

      【解决方案2】:

      用正则表达式拆分:

      let data = "[beginning]<start>How's {the} /weather (\\today%?)[end]";
      let matches = data.split(/\s*(?:<[^>]+>|\[[^\]]+\]|\{[^\}]+\}|[()])\s*/);
      
      console.log(matches.filter(v => "" !== v));

      【讨论】:

      • 所以,我冒昧地使用用户字符串将您的代码变成了一个 sn-p,但我认为它不太有效 - 看看输出什么。除非我错过了什么
      • 通过过滤掉空字符串更新了结果。
      • 请注意,这将包括 OP 想要匹配的字符以外的字符。例如,它目前在\\today%? 中包含?
      【解决方案3】:

      您可以使用alternation 匹配所有不想要的情况,并将字符类放在捕获组中以捕获您想要保留的内容。

      [^ 是一个 negated character class,它匹配除指定字符之外的任何字符。

      (?:\[[^\][]*]|<[^<>]*>|{[^{}]*})|([A-Za-z'/\\%]+)
      

      说明

      • (?:非捕获组
        • \[[^\][]*]从开场到闭幕的比赛[]
        • |或者
        • &lt;[^&lt;&gt;]*&gt;从开场到闭幕的比赛&lt;&gt;
        • |或者
        • {[^{}]*}从开场到闭幕的比赛{}
      • )关闭非捕获组
      • |或者
      • ([A-Za-z'/\\%]+) 重复字符类 1+ 次以防止空匹配并在 group 1 中捕获

      Regex demo

      const regex = /(?:\[[^\][]*]|<[^<>]*>|{[^{}]*})|([A-Za-z'/\\%]+)/g;
      const str = `[beginning]<start>How's {the} /weather (\\\\today%?)[end]`;
      let m;
      
      while ((m = regex.exec(str)) !== null) {
        if (m[1] !== undefined) console.log(m[1]);
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-20
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-05
        • 2019-11-19
        相关资源
        最近更新 更多