Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 7 down vote accepted

The regex to match multiple \ns is


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.replaceAll('\n+', '\n'));

Note the use of replaceAll. Apex has three string replacement methods; they 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


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.