Given a string with the following variations where {br} is a line break not a literal

  1. Line 1{br}Line 2
  2. Line 1{br}{br}Line2
  3. Line 1{br}{br}{br}Line 2{br}

Basically any number of line breaks between lines.

Trying to find the regex that will replace all Single and multiple occurrences (treated as one) with the characters **

Result should be

Line 1 ** Line 2

In all cases from above.

Right now I have this as a solution but I am sure the brains here have a better, smaller, easier way:

String testString = 'Line 1\r\nLine 2\r\n\r\nLine 3';
String[] tmp = testString.split('\\r|\\n');

for(integer x=0;x<tmp.size();x++){

System.debug(String.join(tmp,' ** '));


Line 1 ** Line 2 ** Line 3

Is there an easier way?


This is a good time for replaceAll(regex, replacement):

String testString = 'Line 1\r\nLine 2\r\n\r\nLine 3';
system.debug(testString.replaceAll('(\\r|\\n)+', ' ** '));


Line 1 ** Line 2 ** Line 3

|improve this answer|||||
  • 1
    Aww dang it. I was not using the + and it was causing Line 2 ** ** Line 3. Stupid mistake. Thanks – Eric May 10 '17 at 23:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.