用一些单词查找行,没有其他单词

时间:2012-02-12 20:23:11

标签: java regex

我用正则表达式和java搜索一个方法,用一些单词找到一个文本行而没有其他单词。

例如,我想获得包含单词冰雪的行,但不包含树和滑雪。字顺序并不重要。

我开始用冰雪细纹

(ice)*(snow)

这似乎有效,但如果订单被颠倒,则无效。

编辑:

是否可以返回单词ice and snow之间有3个字母或更多字母的单词

2 个答案:

答案 0 :(得分:2)

我认为regex在这种情况下会有些过分,只需使用String类的String.contains()方法。

String str = "line contains ice and snow";
if(str.contains("ice") && str.contains("snow"))
        System.out.println("contains both");
else
        System.out.println("does not contain both");

输出= contains both

String str = "line contains ice";
if(str.contains("ice") && str.contains("snow"))
        System.out.println("contains both");
else
        System.out.println("does not contain both");

输出= does not contain both

答案 1 :(得分:1)

我同意@RanRag的说法,在这种情况下正则表达式是矫枉过正的,但无论如何它都是如何完成的:

(?=.*\bice\b)(?=.*\bsnow\b)(?!.*\btree\b)(?!.*\bski\b)

(?=...)是一个积极的前瞻,而(?!...)是一个负向前瞻。正则表达式还使用单词边界\b,这样它就不会匹配部分单词。

相关问题