dotwin
dotwin

Reputation: 1332

Java's multiline regex behavior

In multiline mode, I expected Java

"BEGIN\n\n  END".replaceAll("(?m)^\\s+|\\s+$", "")

to result in

"BEGIN\n\nEND"

but instead it results in

"BEGINEND"

What am I missing please?

Upvotes: 1

Views: 50

Answers (1)

anubhava
anubhava

Reputation: 786291

MULTILINE doesn't change interpretation of \n as \s matches all whitespace characters including newline.

You can use \h (horizontal whitespace) instead of \s to make it work (available from Java 8 onwards):

String repl = "BEGIN\n\n  END".replaceAll("(?m)^\\h+|\\h+$", "");

If you are on older Java versions then use this instead of \h: (thanks to @ctwheels)

[^\S\n]

Upvotes: 2

Related Questions