kelly kelly - 4 months ago 23
Java Question

Getting extra line using row seperator

I'm using this regex to split one line into multiple group by 2 characters.

string.replaceAll("(.{2})", "$1\r\n")

Here is an example.

Like my input input string is like this


And output am getting like this


Is there any way so that I don't receive that last empty line?


You have two options:

  • Manually remove the new line from the result
  • Change your regex to: (.{2})(?!$)

Now the regex will catch all pairs except the last one, and you will not be replacing it with a new line.