Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

How to replace multiple '\n's with single '\n'? More specifically, how to write regex to match multiple '\n's?

share|improve this question

1 Answer 1

up vote 6 down vote accepted

That's two questions. The regex to match multiple \ns is

\n+

The plus (+) specifically matches 1 or more occurrences of the proceeding character. You can see it action:

string t = 'hey\n\n\nyou.';
system.debug(t);
system.debug(t.replaceAll('\n+', '\n'));

Note the use of replaceAll. Apex has three string replacement methods; there are all instance methods :

  • replace(String target, String replacement) - replaces all literal (not regex) occurrences of target with replacement.

  • replaceAll(String target, String replacement) - replaces all occurrences of the regex target with replacement

  • replaceFirst(String target, String replacement) - replace the first occurrence of the regex target with replacement

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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