簡體   English   中英

在Java中的分隔符之間匹配多行文本

[英]Match for multiple lines of text between delimiters in Java

如何在Java中的分隔符之間匹配多行文本?

通過示例可以很好地說明問題:

...
unimportant text
EndOfEntry
Key=Value
unimportant text
maybe a few lines of unimportant text
AnotherKey=AnotherValue
EndOfEntry
more unimportant text
...

在上面,我想匹配鍵=值。* AnotherKey = AnotherValue一起出現在一個條目中。 我只是想知道模式是否出現-我不需要替換任何東西。

但是,如果給定多個條目,則具有相同的期望匹配項,例如:

...
unimportant text
EndOfEntry
Key=Value
unimportant text
maybe a few lines of unimportant text
AnotherKey=NotMyValue
EndOfEntry
RandomKey=Value
unimportant text
maybe a few lines of unimportant text
AnotherKey=AnotherValue
EndOfEntry
more unimportant text
...

我不希望上述內容成功匹配,因為我們在單個“條目”中看不到Key = Value和AnotherKey = AnotherValue。 相反,我們在第一個條目中看到Key = Value,在第二個條目中看到AnotherKey = AnotherValue。

我一直在嘗試使用類似的正則表達式(當然\\ S \\ s可以由Pattern的DOTALL選項代替):

Key=Value[\S\s]*?AnotherKey=AnotherValue

但是當然兩者都匹配。 我也嘗試過:

Key=Value[^EndOfEntry]*?AnotherKey=AnotherValue

但這是行不通的,因為那樣就沒有點了,我們根本不匹配換行符。

是否有一個正則表達式可以完全符合我的需求? 它會簡化首先刪除換行符或其他兩步處理(我只是為了教育而避免這樣做)的事情嗎?

您應該簡單地使用:

\bKey=Value\b(?:(?!EndOfEntry).)*?\bAnotherKey=AnotherValue\b

(如您在問題中所建議的,帶有DOTALL標志)。

在regex101上進行實驗


這個怎么運作:

我基本上只是將您的.*替換為該表達式: ((?!EndOfEntry).)* ,它大致表示不包含EndOfEntry任何EndOfEntry

此外,為了避免與RandomKey=ValueAnotherKey=AnotherValue對匹配, AnotherKey=AnotherValue ,由於RandomKey=Value也將匹配Key=Value ,因此,我進行了其他一些調整:

我已經用\\b (斷言我們處於單詞邊界)(或\\s ,對於任何空格字符)包圍了您的配對,所以只有當整個單詞都匹配時我們才匹配。


這是一段Java代碼,使用了我建議針對您的示例使用的正則表達式:

final Pattern pattern = Pattern.compile("\\bKey=Value\\b(?:(?!EndOfEntry).)*?\\bAnotherKey=AnotherValue\\b", Pattern.DOTALL);

final String invalid = "unimportant text\n" +
                "EndOfEntry\n" +
                "Key=Value\n" +
                "unimportant text\n" +
                "maybe a few lines of unimportant text\n" +
                "AnotherKey=NotMyValue\n" +
                "EndOfEntry\n" +
                "RandomKey=Value\n" +
                "unimportant text\n" +
                "maybe a few lines of unimportant text\n" +
                "AnotherKey=AnotherValue\n" +
                "EndOfEntry\n" +
                "more unimportant text";

final String valid = "unimportant text\n" +
                "EndOfEntry\n" +
                "Key=Value\n" +
                "unimportant text\n" +
                "maybe a few lines of unimportant text\n" +
                "AnotherKey=AnotherValue\n" +
                "EndOfEntry\n" +
                "more unimportant text";

System.out.println(pattern.matcher(invalid).find());
System.out.println(pattern.matcher(valid).find());

輸出:

false
true

暫無
暫無

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

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