java - How to match regex over multiple lines -
this question has answer here:
i have body of text , trying find character sequence within it. string.contains()
not work im trying use string.matches
method , regular expression. current regex isn't working. here attempts:
"1stline\r\n2ndline".matches("(?im)^1stline$"); // returns false; 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 format regex returns true?
you need use s
flag (not m
flag).
it's called dotall
option.
this works me:
string input = "1stline\n2ndline\n3rdline"; boolean b = input.matches("(?is).*2ndline.*");
i found here.
note must use .*
before , after regex if want use string.matches()
.
that's because string.matches()
attempts match entire string pattern.
(.*
means 0 or more of character when used in 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 googling "java regex multiline"
, clicking first result.
(it's if answer written you...)
there's ton of info patterns , regexes here.
if want match only if 2ndline
appears @ beginning of line, this:
boolean b = input.matches("(?is).*\\n2ndline.*");
or this:
pattern p = pattern.compile("(?i)\\n2ndline", pattern.dotall);
Comments
Post a Comment