正则表达式查找匹配的3个术语的任意组合

时间:2018-11-10 15:02:11

标签: regex

我需要设计一个正则表达式,它可以匹配n个单词的任意组合,而不能重复。

例如单词"she" "is" "happy"的正则表达式将匹配"she is happy""happy she is"但不匹配"she is is happy""she is"

我可以使用正则表达式进行此操作,因为我应该使用自定义算法吗?

1 个答案:

答案 0 :(得分:2)

此匹配项she is happy可以按任意顺序排列,但不能重复:

^(?=(?:(?!\bshe\b).)*\bshe\b(?:(?!\bshe\b).)*$)(?=(?:(?!\bis\b).)*\bis\b(?:(?!\bis\b).)*$)(?=(?:(?!\bhappy\b).)*\bhappy\b(?:(?!\bhappy\b).)*$).*$

DEMO

让我们解释第一部分(即(?=(?:(?!\bshe\b).)*\bshe\b(?:(?!\bshe\b).)*$)

请确保我们在词组中的任何地方只有一个只有一个“她”。

(?=                     # start lookahead
    (?:                 # non capture group
        (?!\bshe\b)     # negative lookahead, make sure we don't have "she"
        .               # any character
    )*                  # end group, may appear 0 or more times
    \bshe\b             # literally "she" surounded by word boundaries
    (?:                 # non capture group
        (?!\bshe\b)     # negative lookahead, make sure we don't have "she"
        .               # any character
    )*                  # end group, may appear 0 or more times
    $
)

“ is”和“ happy”这两个词的解释相同。

相关问题