【问题标题】:REGEX: Match strings that contain a specific word but not strings that merely contain that wordREGEX:匹配包含特定单词的字符串,但不匹配仅包含该单词的字符串
【发布时间】:2022-11-19 19:13:00
【问题描述】:

例如,我想匹配所有包含单词“cat”或“dog”的字符串,例如 concatenation、doghouse、underdog、catastrophe 或 endogamy。但我想排除狗或猫这两个词的匹配。我使用以下正则表达式尝试了此任务。

\\w*(cat|dog)(s(?=\w+))*\

但是这个正则表达式不能帮助我选择 s 之后的任何内容。还有其他方法可以实现这一目标吗?任何帮助表示赞赏。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    这个正则表达式应该工作

    const regex = /(?!cats|dogs)[a-z]*(?:cat|dog)[a-z]*/gi;
    const m = 'concatenation, doghouse, underdog, catastrophe, endogamy should match, but not cats and dogs.'.match(regex);
    console.log(m);

    输出:

    [
      "concatenation",
      "doghouse",
      "underdog",
      "catastrophe",
      "endogamy"
    ]
    

    正则解释:

    • -- 单词边界
    • (?!cats|dogs)——仅针对catsdogs的否定前瞻
    • [a-z]* -- 可选字母字符
    • (?:cat|dog)——文字catdog的非捕获组
    • [a-z]* -- 可选字母字符
    • -- 单词边界

    【讨论】:

      猜你喜欢
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多