You need to use the s
flag (not the m
flag).
It's called the DOTALL option.
This works for me:
String input = "1stline\n2ndLINE\n3rdline";
boolean b = input.matches("(?is).*2ndline.*");
I found it here.
Note you must use .*
before and after the regex if you want to use String.matches().
That's because String.matches() attempts to match the entire string with the pattern.
(.*
means zero or more of any character when used in a regex)
Another approach, found here:
String input = "1stline\n2ndLINE\n3rdline";
Pattern p = Pattern.compile("(?i)2ndline", Pattern.DOTALL);
Matcher m = p.matcher(input);
boolean b = m.find();
print("match found: " + b);
I found it by googling "java regex multiline" and clicking the first result.
(it's almost as if that answer was written just for you...)
There's a ton of info about patterns and regexes here.
If you want to match only if 2ndline
appears at the beginning of a line, do this:
boolean b = input.matches("(?is).*\\n2ndline.*");
Or this:
Pattern p = Pattern.compile("(?i)\\n2ndline", Pattern.DOTALL);