This question already has an answer here:
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 them
flag).It's called the
DOTALL
option.This works for me:
I found it here.
Note you must use
.*
before and after the regex if you want to useString.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:
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:Or this:
You could try using
contains
It would be something like
btw, using same example that @wdziemia, I'm not expert at REGEX either... :)
hope it helps.
If you are trying to see if
"1stLine"
exists within the string"1stline\r\n2ndline\r\n3rdLine"
then you could just do the following:----------------------------EDIT----------------------------
So for some reason .contains wont work in your test. Here is the regular expression to find the string "1stline"