4

I have the following file contents and I'm trying to match a reg explained below:

-- file.txt (doesn't match multi-line) -- test On blah more blah wrote: --------------- 

If I read the file contents from above to a String and try to match the "On...wrote:" part I cannot get a match:

 // String text = <file contents from above> Pattern PATTERN = Pattern.compile("^(On\\s(.+)wrote:)$", Pattern.MULTILINE); Matcher m = PATTERN.matcher(text); if (m.find()) { System.out.println("Never gets HERE???"); } 

The above regex works fine if the contents of the file are on one line:

-- file2.txt (matches on single line) -- test On blah more blah wrote: On blah more blah wrote: --------------- 

How do I get the multiline to work and the single line all in one regex (or two for that matter)? Thx!

2 Answers 2

3

Pattern.MULTILINE just tells Java to accept the anchors ^ and $ to match at the start and end of each line.

Add the Pattern.DOTALL flag to allow the dot . character to match newline characters. This is done using the bitwise inclusive OR | operator

Pattern PATTERN = Pattern.compile("^(On\\s(.+)wrote:)$", Pattern.MULTILINE | Pattern.DOTALL ); 
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! Worked the first time as advertised! Thank you!
1

You could use a combination of matching \S (non-whitespace) and \s (whitespace)

Pattern PATTERN = Pattern.compile("(On\\s([\\S\\s]*?)wrote:)"); 

See live regex101 demo

Example:

import java.util.regex.*; class rTest { public static void main (String[] args) { String s = "test\n\n" + "On blah\n\n" + "more blah wrote:\n"; Pattern p = Pattern.compile("(On\\s([\\S\\s]*?)wrote:)"); Matcher m = p.matcher(s); if (m.find()) { System.out.println(m.group(2)); } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.