WraithLux
WraithLux

Reputation: 699

Java string regex matches fails with linebreak?

StringBuilder testSB = new StringBuilder();
String testString = "error 1:";
int times = 0;
while(times<=10){
    testSB.append(testString +"\n");
    times++;
}

String testResponse  = "error 1:";
String realResponse = testSB.toString();

Log.i("REAL", String.valueOf(realResponse.matches(".*error.*")));
Log.i("TEST", String.valueOf(testResponse.matches(".*error.*")));

The "real" string does not match, while the "test" string does. If I remove +"\n" from the while block, it matches regexp. I thought .* would apply for new line as well?

Upvotes: 0

Views: 2902

Answers (2)

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33273

Whether . matches line terminators depends on if MULTILINE mode is activated. See the java documentation for java.util.regex.Pattern.

Upvotes: 1

pap
pap

Reputation: 27614

. does not match newline by default, but if you add the (?s) switch at the beginning of your regexp, it will.

Upvotes: 6

Related Questions