什么是正则表达式公式来匹配正文中的两组单词

时间:2018-11-22 12:24:52

标签: regex

如果文本正文中包含“ delta”或“ gamma”,请向我显示匹配“ alpha”或“ beta”的公式。

文字示例:

詹姆斯是阿尔法,但不是伽玛,但他也可能是三角洲

这应该是一个匹配项,因为文本中同时包含“ alpha”和“ gamma”。

我也希望它也匹配,因为文本中同时包含“ alpha”和“ delta”。

如果在文本示例中将“ alpha”替换为“ beta”,则匹配公式也应适用。

2 个答案:

答案 0 :(得分:0)

如果您需要按任一顺序匹配配对,则可以使用lookahead assertions

^(?=.*\b(?:alpha|beta)\b)(?=.*\b(?:gamma|delta)\b).*

测试live on regex101.com

说明:

每个前行检查字符串中某处是否存在两个术语之一。为了使比赛继续进行,两个先行者都需要成功。最后的.*并不是绝对必要的(只是为了使正则表达式测试器中的匹配可视化);如果您只需要检查匹配/不匹配,则可以将其删除。在这种情况下,匹配结果将为空字符串。

答案 1 :(得分:0)

根据您的正则表达式口味,这对您有效:

^                   # beginning of line
    (?=             # start lookahead, zero-lengh assertion that make sure we have within a line
        .*          # 0 or more any character but newline
        \b          # word boundary
        (?:         # start non capture group
            delta   # literally "delta"
          |         # OR
            gamma   # literally "gamma"
        )           # end group
        \b          # word boundary
    )               # end lookahead
    .*              # 0 or more any character but newline
    \b              # word boundary
    (               # start group 1
        alpha       # literally "alpha"
      |             # OR
        beta        # literally "beta"
    )               # end group
    \b              # word boundary
    .*              # 0 or more any character but newline
$                   # end of line

DEMO