+ Start a Discussion
Chris760Chris760 

Method that returns only the numbers in a string?

I often times run into scenarios where I need to extract phone, fax, or mobile numbers from phone or string fields and then get rid of everything but the numbers (for verification/comparison purposes, deduping, or to run other automation that wont accept non-numbers).  Currently, I do a PhoneNumber.replace('(','').replace(')','').replace('.','').replace('-','').replace(' ','').replace('+','') etc etc type of thing to get rid of every charachter I can think of that might muck up the trigger, but it's obviously not very efficient because not only is it long, but people still throw in charachters occasionally that I didn't account for.

 

Is there some kind of method in Apex that can automatically extract all the numbers in a string, in the same order that they appear in the string?  Or can anyone think of another apex method (or approach) that might act as a nice little shortcut?

 

Any ideas from more experienced programmers would be really appreciated.  Thanks.

Satish_SFDCSatish_SFDC

Not too efficient but still works. 

 

String str = '123.345,456';
String numericString = '';
integer strLength = str.length();
for(integer i =0;i<str.length();i++){
    String s= str.mid(i,1);
    if(s.isNumeric()){
        numericString +=s;
    }
}
System.debug('Number is: ' + numericString);

 

Regards,
Satish Kumar
Please mark my answer as a solution if it was helpful so it is available to others as a proper solution.
If you felt I went above and beyond, please give me Kudos by clicking on the star icon.