8

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++){
    if(tmp[x].isWhitespace()){
        tmp.remove(x);
        x--;
    }
}

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

Results

Line 1 ** Line 2 ** Line 3

Is there an easier way?

1 Answer 1

13

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)+', ' ** '));

Results:

Line 1 ** Line 2 ** Line 3

1
  • 1
    Aww dang it. I was not using the + and it was causing Line 2 ** ** Line 3. Stupid mistake. Thanks
    – Eric
    May 10, 2017 at 23:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .