apexDeveloper
apexDeveloper

Reputation: 3

Trying to unformatted phone number from (999) 777-8888 this to this 9997778888 format

My apex code below extracts phone number from Subject field in the Case object. The thing is that I can't compare with Account Phone field because Phone field is only numbers just like this 9998887777. I tried different solution using pattern but no luck so far and I m stuck. Any help appreciated.

public class PhoneNumberExtract {


    @InvocableMethod(label = 'Extract Phone Number' description = 'Extract phone number from Subject field in Case object')
    public static List<String> extractPhoneNum(List<Case> cases){
        List<String> lstString = new List<String>();
        for (Case recCase : cases) {
            for (Integer i=0; i < recCase.Subject.length(); i++) {
                if (recCase.Subject.subString(i, i+1) == '(') {
                    lstString.add(recCase.Subject.subString(i,i+14));
                    break;
                }
            }
        }
        String finalString = lstString.get(0);
        finalString.replace('[()\s-]', '');
        List<String> lstStringFinal = finalString.split(',');
        return lstStringFinal;
    }
}

I tried using pattern but it didnt work

String finalString = lstString.get(0);
        finalString.replace('[()\s-]', '');
        List<String> lstStringFinal = finalString.split(',');
        return lstStringFinal;

Upvotes: 0

Views: 52

Answers (1)

Umesh Rana
Umesh Rana

Reputation: 1

try this code

String sampleText = '(999) 987-6541';
// exclude all characters which you want to keep 
System.debug(sampleText.replaceAll('[^\\d]',''));

Upvotes: 0

Related Questions