kelly kelly - 13 days ago 5
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

ABCDEFGHIJ


And output am getting like this

Output
->AB
->CD
->EF
->GH
->IJ
->


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

Answer

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.