Reputation: 4651
I have a String string
that contains a newline (\n
). When I try to match it with a regular expression pattern
it returns false, although there should be a match.
package com.stackoverflow;
public class ExgExTest {
public static void main(String[] args) {
String pattern = ".*[0-9]{2}[A-Z]{2}.*";
String string = "123ABC\nDEF";
if (string.matches(pattern)) {
System.out.println("Matches.");
} else {
System.out.println("Does not match.");
}
} // END: main()
} // END: class
How can I match multiline strings with a regular expression?
Upvotes: 2
Views: 136
Reputation: 2101
You should use Pattern.quote(pattern)
to escape all special characters in the pattern.
Upvotes: 0
Reputation: 786291
How can I match multiline strings with a regular expression?
You need to use DOTALL
(s
) flag for this:
String pattern = "(?s).*[0-9]{2}[A-Z]{2}.*";
Take note of (?s)
which will make DOT
match new lines also.
Upvotes: 3