正则表达式将所有内容匹配为空行

时间:2016-05-22 09:43:36

标签: java regex

我已经试了好几个小时了,我确定我错过了一些简单的事情。 我试图在Java中创建一个带有一些文本并提取其中一部分的方法。

我希望匹配“注释”中的所有内容。到此后的第一个空白行

示例输入

Some info about stuff
Notes: THis is a note about other stuff
So is this
    And this

This is something else

输入可以是不同的长度,也可以是

  BLabla
    Notes: Hello hello
        So is this
            And this
    And this too
    also

 Now I have something else to say

需要的输出: 例1

Notes: THis is a note about stuff
So is this
    And this

示例2

 Notes: Hello hello
        So is this
            And this
    And this too
    also

我试过了:

public static String NotesExtractor(String str){
        String mynotes=null;
        str=str+"\n\n"+"ENDOFLINE";
        Pattern Notesmatch_pattern = Pattern.compile("Notes:(.*?)^\\s*$",Pattern.DOTALL);
        Matcher Notesmatchermatch_pattern = Notesmatch_pattern.matcher(str);
        if (Notesmatchermatch_pattern.find()) {     
        String h = Notesmatchermatch_pattern.group(1).trim();
        mynotes=h;

    }
        mynotes=mynotes.replaceAll("^\\n", "").trim();
        return mynotes;

    }

但我没有得到任何比赛,我不知道为什么。

1 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式

(?s)Notes.*?(?=\n\n)

<强> Regex Demo

Java代码

String line = "Some info about stuff\nNotes: THis is a note about other stuff\nSo is this\n    And this\n\nThis is something else"; 
String pattern = "(?s)Notes.*?(?=\n\n|$)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);

if (m.find()) {
    System.out.println(m.group());
}

<强> Ideone Demo