Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.matches() with \n

Tags:

java

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
    }    
}
like image 302
W W Avatar asked Oct 24 '25 08:10

W W


1 Answers

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));
like image 73
Indent Avatar answered Oct 26 '25 22:10

Indent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!