Using regex in replaceAll to replace multiple char in one go

1.6K    Asked by FreemanPacifico in Salesforce , Asked on Apr 22, 2021

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?

Answered by Ira Joshi

You can Try this to replaceall:

        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)


Your Answer

Interviews

Parent Categories