Reputation: 799
Why the String::matches
method returns false
when the string contains \n
?
public class AppMain2 {
public static void main(String[] args) {
String data1 = "\n London";
System.out.println(data1.matches(".*London.*")); // false
}
}
Upvotes: 4
Views: 1805
Reputation: 4967
If you want matches
to return true
, you need to use (?s)
or Pattern.DOTALL
.
This way .
matches any character including \n
System.out.println(data1.matches("(?s).*London.*"));
or:
Pattern pattern = Pattern.compile(".*London.*", Pattern.DOTALL);
System.out.println(data1.matches(pattern));
Upvotes: 5
Reputation: 517
"\n" considered as newline so String.matches searching for the pattern to in new line.so returning false try something like this.
Pattern.compile(".London.", Pattern.MULTILINE);
Upvotes: -1
Reputation: 116538
By default Java's .
does not match newlines. To have .
include newlines, set the Pattern.DOTALL
flag with (?s)
:
System.out.println(data1.matches("(?s).*London.*"));
Note for those coming from other regex flavors, the Java documentation use of the term "match" is different from other languages. What is meant is Java's string::matches()
returns true only if the entire string is matched, i.e. it behaves as if a ^
and $
were added to the head and tail of the passed regex, NOT simply that it contains a match.
Upvotes: 2
Reputation: 1060
It doesn't match because "." in regex may not match line terminators as in the documentation here :
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#sum
Upvotes: 2