我有一個術語,比如說dog和一組預定義標簽的示例:red和big. 我正在嘗試撰寫一個匹配有效字串的正則運算式 - 那些具有標簽的任意組合的標簽可能會遇到零次或一次。標簽順序無關緊要。
應匹配的字串示例:
dog
red dog
red big dog
big red dog
不應匹配的字串示例:
red red dog
red big red dog
small red dog
僅列舉所有可能的組合的直接方法是數十個術語的噩夢。
這是我現在停下來的地方:
/
(?: # group for repetition
(
red\s | big\s # a tag that ...
)(?! \1 ) # ... is not followed by itself
# > (replacing backref with a recusional backref
# > still doesn't work,
# > changing negative lookahead by a positive
# > still gives same undesired match on invalid strings)
){0,2} # such a term repeated 0 to [amount of terms] times
dog # followed by a 'dog'
/xs
此正則運算式匹配所有字串,這是不希望的。
uj5u.com熱心網友回復:
你可以使用這個正則運算式:
^(?!.*\b(big|red)\h.*\b\1\b)(?:big\h |red\h )*dog$
正則運算式演示
正則運算式詳細資訊:
^: 開始^(?!.*\b(big|red)\h.*\b\1\b): 如果任何關鍵字出現多次,則匹配失敗(?:big\h |red\h )*: 匹配 0 個或多個bigorred后跟 1 個空格的單詞dog: 匹配dog$: 結尾
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/480733.html
