Sebastian Zeki
Sebastian Zeki

Reputation: 6874

Regex to match everything to a blank line

I've tried for hours and I'm sure I'm missing something simple. I'm trying to create a method in Java that takes some text and extracts a part of it.

I'd like to match everything from 'Notes' to the first blank line after this

Example input

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

This is something else

The input can be of varying lengths so could also be

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

 Now I have something else to say

Needed output: Example 1

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

Example 2

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

I've tried:

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;

    }

but I don't get any matches and I'm not sure why.

Upvotes: 2

Views: 1445

Answers (1)

rock321987
rock321987

Reputation: 11042

You can use this regex

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

Regex Demo

Java Code

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

Upvotes: 3

Related Questions