2013-09-01 22 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