簡體   English   中英

使用正則表達式Java的行之間的子字符串

[英]Substring between lines using Regular Expression Java

嗨,我有以下字符串

abc test ...
interface
somedata ...
xxx ...
!
sdfff as ##
example
yyy sdd @# .
!

我有一個要求,我想在具有單詞“ interface”或“ example”的行與“!”行之間找到內容。
所需的輸出如下所示

String[] output= {"somedata ...\nxxx ...\n","yyy sdd @# .\n"} ;

我可以使用substring和eration手動進行此操作。 但是我想使用正則表達式來實現。 可能嗎?

這就是我嘗試過的

String sample="abc\ninterface\nsomedata\nxxx\n!\nsdfff\ninterface\nyyy\n!\n";
    Pattern pattern = Pattern.compile("(?m)\ninterface(.*?)\n!\n");
    Matcher m =pattern.matcher(sample);
    while (m.find()) {
        System.out.println(m.group());
    }

我對嗎? 請提出正確的做法。

編輯:

一個小變化:我想在“接口”或“示例”行與“!”行之間找到內容。

我們也可以使用正則表達式來實現嗎?

您可以使用(?s) DOTALL修飾符。

String sample="abc\ninterface\nsomedata\nxxx\n!\nsdfff\ninterface\nyyy\n!\n";
Pattern pattern = Pattern.compile("(?s)(?<=\\ninterface\\n).*?(?=\\n!\\n)");//Pattern.compile("(?m)^.*$");
Matcher m =pattern.matcher(sample);
while (m.find()) {
    System.out.println(m.group());
}

輸出:

somedata
xxx
yyy

請注意,示例中的輸入是不同的。

  • (?<=\\\\ninterface\\\\n)斷言匹配必須以與正向后方內部存在的模式匹配的字符為開頭。

  • (?=\\\\n!\\\\n)斷言必須在匹配項后跟與正向超前查詢中存在的模式匹配的字符。

更新:

Pattern pattern = Pattern.compile("(?s)(?<=\\n(?:example|interface)\\n).*?(?=\\n!\\n)");

暫無
暫無

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

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