[SalesForce] using regex in replaceAll to replace multiple char in one go

I have a phone number that i need to convert to a valid format to be send to a webservice validator. The phone number should be 10 char long and should contains only digits.

For instance, I should convert

 +567 231 34 34 to 5672313434
 (567)231-34-34 to 5672313434 

before sending

I have the solution which does the replacement in apex :

   String t = '+571 567 65 77';
   String r = t.replaceAll('\\(','');
   r = r.replaceAll('\\)','');
   r = r.replaceAll('-','');
   r = r.replaceAll('\\+','');
   r = r.replaceAll('\\s','');
   system.debug('## final result is :' + r);

Can I obtain the result in a single line?

Best Answer

Try this:

String r = t.replaceAll('[^0-9]','');

Explanation:

Instead of hunting for invalid characters and removing them explicitly you can specify remove all characters other than numbers.

  • ^ for not a given char
  • [0-9] for numbers ranging from 0 to 9
  • '' replace it with empty char (removes it from our string)
Related Topic