Reputation: 1805
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
Reputation: 784948
Since you are trying to match a string with overlapping matches, you need to use a lookahead assertion:
(\n (?=\n))+
(?=\n)
is zero-width assertion that doesn't match just asserts presence of \n
ahead of current position.
Upvotes: 7