Trying to replace a character '+' with underscore. Tried:

String s = 'Happy+Me';
System.debug(s.replaceAll('\\+', '_');
System.debug(s.replaceAll('/\[+]', '_');

Still gives me 'Happy+Me' result. Well it doesn't seem to work.

  • N.B. re: sfdcfox's answer: Option 1 works on strings longer than 1MB; option 2 will throw an uncatchable regex too complicated error if used on strings > 1 MB – cropredy Mar 11 '19 at 17:29

you have not close bracket. use this below code

 String s = 'Happy+Me';
 System.debug(s.replaceAll('\\+', '_'));
|improve this answer|||||
  • Oops sorry about that, Im just typing my code while asking, not copying and pasting it. – Miguel Gaurano Punzal Mar 11 '19 at 10:07

Option 1

Use replace instead of replaceAll:


Option 2

Use the appropriate regular expression for replaceAll. Note that regular expressions use \ to escape, but Apex also uses \ to escape. This means you need to use twice as many \ to get the correct result:


To match a literal \ in a regular expression string, you would need to use four \ total:

System.debug('Hello\\World'.replace('\\\\',' '));

If you're using a Custom Label or other source for your regular expression string, you would not need to escape the \, as this only applies during the compilation of Apex code.

|improve this answer|||||

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.