我想在一个正则表达式中组合一个 AND 和一个 OR 运算。
我有两套标签。集合 A 和集合 B。在集合内我需要一个 OR 操作,在集合之间需要一个 AND。
例子:
Set A has 3 values:
A1, A2, A3
Set B has 2 values:
B1 and B2
示例搜索操作:
A1 OR A2 AND B2
A2 OR A3 AND B1 OR B2
...
知道如何实现吗?
最佳答案
Within a set i need an OR operation and between Sets an AND.
您可以像这样使用前瞻:
^(?=.*?(?:A1|A2|A3))(?=.*?(?:B1|B2)).*$
描述:
(?=.*?(?:A1|A2|A3)) Positive Lookahead - Assert that the regex below can be matched
.*? matches any character (except newline)
Quantifier: Between zero and unlimited times, as few times as possible, expanding as needed
(?:A1|A2|A3) Non-capturing group
1st Alternative: (null, matches any position)
2nd Alternative: A1
A1 matches the characters A1 literally (case sensitive)
3rd Alternative: A2
A2 matches the characters A2 literally (case sensitive)
4th Alternative: A3
A3 matches the characters A3 literally (case sensitive)
(?=.*?(?:B1|B2)) Positive Lookahead - Assert that the regex below can be matched
.*? matches any character (except newline)
Quantifier: Between zero and unlimited times, as few times as possible, expanding as needed
(?:B1|B2) Non-capturing group
1st Alternative: (null, matches any position)
2nd Alternative: B1
B1 matches the characters B1 literally (case sensitive)
3rd Alternative: B2
B2 matches the characters B2 literally (case sensitive)
关于javascript - 在正则表达式中组合 AND 和 OR 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21670287/