using regex in replaceAll to replace multiple char in one go

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)

You can use ReplaceAll method

try Like this

String t = '(567)231-34-34';
String r = t.replaceAll('[^\\d]','');
system.debug('## final result is :' + r);

String t1 = '+567 231 34 34';
String r1 = t1.replaceAll('[^\\d]','');
system.debug('## final result is :' + r1);

Reference:

  • ^ - Negates character class.
  • \d - any digit character same as [0-9]

Debug logs

13:27:40:044 USER_DEBUG [3]|DEBUG|## final result is :5672313434
13:27:40:044 USER_DEBUG [7]|DEBUG|## final result is :5672313434


Another option

String t = '(567)231-34-34';
String r = t.replaceAll('[-+()s]','');
system.debug('## final result is :' + r);

String t1 = '+567 231 34 34';
String r1 = t1.replaceAll('[-+()s]','');
system.debug('## final result is :' + r1);

Reference:

  • [ ] Demarcates a character class. To interpret literally, use a backslash.
  • [abc] is a character class that means "any character from a,b or c" (a characer class may use ranges, eg [a-d] = [abcd])

Debug logs

13:26:13:004 USER_DEBUG [3]|DEBUG|## final result is :5672313434
13:26:13:004 USER_DEBUG [7]|DEBUG|## final result is :567 231 34 34