2014-02-10 27 views
2

我想在一個正則表達式中組合AND和OR操作。在正則表達式中組合AND和OR操作符

我確實有2組標籤。設置A和設置B.在設置我需要一個或操作之間和設置一個與。

例子:

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 
... 

任何想法如何,我可以做到這一點?

回答

1

在一個集合中,我需要一個OR操作,並在集合之間設置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) 
+0

符合OP的規範將匹配'「A1 B1」'。 – Amadan

+0

這個問題有些矛盾。它也說'在一組中我需要一個OR操作,並且在設置一個AND之間,並且按照這個規範'A1和B1'是正確匹配的。 – anubhava

+0

'「A1和B1」'可能是正確的。 '「A1 B1」'不是。在每個元素之間應該有一個運算符(限制在不同集合的元素之間不會有「或」)。 – Amadan

0

我會提交正則表達式是這裏的錯誤的工具。你想要一個解析器。或者,更簡單地說,將您的字符串拆分爲"AND",然後對每個元素拆分"OR",並檢查所有標籤是否在同一個集合中。