2

Why the String::matches method return false when I put \n into the String?

public class AppMain2 {

    public static void main(String[] args) {

        String data1 = "\n  London";

        System.out.println(data1.matches(".*London.*"));
    }

}
W W
  • 769
  • 1
  • 11
  • 26
  • Possible duplicate of [Regular expression does not match newline obtained from Formatter object](https://stackoverflow.com/questions/11644100/regular-expression-does-not-match-newline-obtained-from-formatter-object) http://idownvotedbecau.se/noresearch/ – Oleg Nov 06 '17 at 09:46

4 Answers4

2

If you want true, you need use Pattern.DOTALL or (?s).

By this way . match any characters included \n

String data1 = "\n  London";
Pattern pattern = Pattern.compile(".*London.*", Pattern.DOTALL);
System.out.println(data1.matches(pattern));

or :

System.out.println(data1.matches("(?s).*London.*"));
Indent
  • 4,675
  • 1
  • 19
  • 35
2

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

Venom
  • 1,010
  • 10
  • 20
2

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.

lc.
  • 113,939
  • 20
  • 158
  • 187
-1

"\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);

Harsh Maheswari
  • 467
  • 5
  • 3