Axel Axel - 1 year ago 75
Java Question

Regular expression does not match newline obtained from Formatter object

I cannot match a String containing newlines when the newline is obtained by using

object or
. Please have a look at the following program:

public class RegExTest {

public static void main(String[] args) {
String input1 = String.format("Hallo\nnext line");
String input2 = String.format("Hallo%nnext line");
String pattern = ".*[\n\r].*";
System.out.println(input1+": "+input1.matches(pattern));
System.out.println(input2+": "+input2.matches(pattern));


and its output:

next line: true
next line: false

What is going on here? Why doesn't the second string match?

Java version is 1.6.0_21.

Answer Source

You can set the Pattern.DOTALL flag to make . match newlines, as default it doesn't. It is done with the (?s) notation. So, this regex does what you want:

    String pattern = "(?s).*[\n\r].*";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download