I have a body of text and I am trying to find a character sequence within it. String.contains() will not work so Im trying to use String.matches method and a regular expression. My current regex isn't working. Here are my attempts:
"1stline\r\n2ndline".matches("(?im)^1stline$");
// returns false; I expect true
"1stline\r\n2ndline".matches("(?im)^1stline$")
// returns false
"1stline\r\n2ndline\r\n3rdline".matches("(?im)^2ndline$")
"1stline\n2ndline\n3rdline".matches("(?im)^2ndline$")
"1stline\n2ndline\n3rdline".matches("(?id)^2ndline$")
How should i format my regex so that it returns true?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With