我需要设计一个正则表达式,它可以匹配n个单词的任意组合,而不能重复。
例如单词"she"
"is"
"happy"
的正则表达式将匹配"she is happy"
,"happy she is"
但不匹配"she is is happy"
或"she is"
。
我可以使用正则表达式进行此操作,因为我应该使用自定义算法吗?
答案 0 :(得分:2)
此匹配项she is happy
可以按任意顺序排列,但不能重复:
^(?=(?:(?!\bshe\b).)*\bshe\b(?:(?!\bshe\b).)*$)(?=(?:(?!\bis\b).)*\bis\b(?:(?!\bis\b).)*$)(?=(?:(?!\bhappy\b).)*\bhappy\b(?:(?!\bhappy\b).)*$).*$
让我们解释第一部分(即(?=(?:(?!\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”这两个词的解释相同。