簡體   English   中英

用一些單詞找到行而沒有其他單詞

[英]Find line with some word and without some other

我用正則表達式和Java搜索一種方法來查找帶有一些單詞而沒有其他單詞的文本行。

例如,我想得到既包含單詞ice和snow但不包含樹和ski的行。 單詞順序並不重要。

我開始與冰雪融為一體

(ice)*(snow)

這似乎有效,但是如果順序倒置,則無效。

編輯:

是否有可能在單詞“ ice”和“ snow”之間返回三個字母或更多的單詞

我認為在這種情況下,僅使用String類的String.contains()方法, regex將是一個矯kill過regex方法。

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

我同意@RanRag的觀點,在這種情況下,正則表達式是過大的,但是無論如何這是可以做到的:

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

(?=...)是正向前瞻,而(?!...)是負向前瞻。 正則表達式還使用單詞邊界\\b因此它不會匹配單詞的一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM