Searched by: java regex between multiple lines
Source URL:
https://stackoverflow.com/questions/3651725/match-multiline-text-using-regular-expression
First, you're using the modifiers under an incorrect assumption.
Pattern.MULTILINE
or (?m)
tells Java to accept the anchors ^
and $
to match at the start and end of each line (otherwise they only match at the start/end of the entire string).Pattern.DOTALL
or (?s)
tells Java to allow the dot to match newline characters, too.
Second, in your case, the regex fails because you're using the
matches()
method which expects the regex to match the entire string - which of course doesn't work since there are some characters left after (\\W)*(\\S)*
have matched.
So if you're simply looking for a string that starts with
User Comments:
, use the regex^\s*User Comments:\s*(.*)
with the
Pattern.DOTALL
option:Pattern regex = Pattern.compile("^\\s*User Comments:\\s+(.*)", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group(1);
}
ResultString
will then contain the text after User Comments: