2013-09-01 21 views
4

我試圖把一個邏輯匹配條件,如:阿帕奇豬 - 賽事有多個匹配標準

(("Foo" OR "Foo Bar" OR FooBar) AND ("test" OR "testA" OR "TestB")) OR TestZ 

,並使用

result = filter inputfields by text matches (some regex expression here)); 

問題將此作爲對豬文件匹配我不知道如何將上面的邏輯表達式轉換爲匹配方法的正則表達式。

我已經擺弄周圍的各種事物和我來最接近的是這樣的:

((?=.*?\bFoo\b | \bFoo Bar\b))(?=.*?\bTestZ\b) 

任何想法?如果可能,我還需要嘗試以編程方式進行此轉換。

一些例子:

一個 - 敏捷的棕色富跳過了懶惰的測試(這應該通過,因爲它包含foo和測試)

b - 的東西在TestZ事情(這也傳遞因爲它包含testZ)

c - 接收敏捷的棕色富跳過了懶狗(這應該會失敗,因爲它包含的Foo但不可考,種皮或TE​​STB)

感謝

+0

for鷹眼,theres失蹤「)」或「TestZ」之前。請忽略此錯字。謝謝 – user2495234

+0

如果這個錯字不是故意的,你可以使用下面的[[edit]]選項來糾正它,而不是通知其他人:) – Pshemo

+0

我有幾個想法如何寫你的正則表達式,但它的形式取決於你有什麼輸入和什麼結果你期望。現在我不確定在'foo bar'部分之後是否強制'test'。如果是這樣,它也應該包括在比賽中(你正在使用前瞻(?= ...),所以可能不會)。你還在說'OR TestZ'應該有'''所以說'TestZ'對單個匹配來說足夠了嗎? – Pshemo

回答

12

由於您使用的豬,你實際上並不需要一個複雜的正則表達式,你可以使用由豬提供的布爾運算符結合幾個簡單的正則表達式,例如:

T = load 'matches.txt' as (str:chararray); 
F = filter T by ((str matches '.*(Foo|Foo Bar|FooBar).*' and str matches '.*(test|testA|TestB).*') or str matches '.*TestZ.*'); 
dump F; 
1

您可以使用此正則表達式matches方法

^((?=.*\\bTestZ\\b)|(?=.*\\b(FooBar|Foo Bar|Foo)\\b)(?=.*\\b(testA|testB|test)\\b)).* 
  • 注意"Foo" OR "Foo Bar" OR "FooBar"應該寫成FooBar|Foo Bar|FooFoo|Foo Bar|FooBar防止只匹配Foo中包含字符串FooBarFoo Bar
  • 也因爲先行爲零寬度您需要在正則表達式的末尾傳遞.*以讓匹配匹配整個字符串。

演示

String[] data = { "The quick brown Foo jumped over the lazy test", 
     "the was something going on in TestZ", 
     "the quick brown Foo jumped over the lazy dog" }; 
String regex = "^((?=.*\\bTestZ\\b)|(?=.*\\b(FooBar|Foo Bar|Foo)\\b)(?=.*\\b(testA|testB|test)\\b)).*"; 
for (String s : data) { 
    System.out.println(s.matches(regex) + " : " + s); 
} 

輸出:

true : The quick brown Foo jumped over the lazy test 
true : the was something going on in TestZ 
false : the quick brown Foo jumped over the lazy dog 
+0

非常感謝...我會把它解釋出來...以及麻煩豬的建議 – user2495234