简体   繁体   中英

String.matches() with \n

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.*"));
    }

}

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.*"));

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

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, ie it behaves as if a ^ and $ were added to the head and tail of the passed regex, NOT simply that it contains a match.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM