简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM