salesforceapexapex-codesalesforce-developer

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;

Solution

  • List<String> extractedNumbers = new List<String>();
        Pattern phonePattern = Pattern.compile('\\(?\\d{3}\\)?[-\\.\\s]?\\d{3}[-\\.\\s]?\\d{4}');
        
       for (Case recCase : cases) {
            if (recCase.Subject != null) {
                Matcher matcher = phonePattern.matcher(recCase.Subject);
    
                if (matcher.find()) {
                    String rawPhoneNumber = matcher.group(0);  // Extract the phone number
                    String cleanedPhoneNumber = rawPhoneNumber.replaceAll('[^\\d]', ''); // Remove non-numeric characters
                    extractedNumbers.add(cleanedPhoneNumber);
                }
            }
        }