Roman Cherepanov
Roman Cherepanov

Reputation: 1805

How to replace all group occurrences in Java?

I want to replace all occurrences of \n \n with \n\n (<new line><space><new line> to <new line><new line>).

I use this code:

assertThat(
    "\n\n \n \n".replaceAll("(\n \n)+", "\n\n"),
    is("\n\n\n\n")
);

But instead of \n\n\n\n I get \n\n\n \n.

How can I fix regex to get right result?

Upvotes: 1

Views: 62

Answers (1)

anubhava
anubhava

Reputation: 784948

Since you are trying to match a string with overlapping matches, you need to use a lookahead assertion:

(\n (?=\n))+

RegEx Demo

(?=\n) is zero-width assertion that doesn't match just asserts presence of \n ahead of current position.

Upvotes: 7

Related Questions