Remove non-numeric characters from a field

apex

I'm getting a field through an integration with Wookie, but this field can come with letters and I'm only interested in the number. At the moment I'm doing the following to remove the letters:

if(results.containsKey('capital_social') && String.isNotBlank(String.valueOf(results.get('capital_social')))){
    //acc.Capital_Social__c = Decimal.valueOf( String.valueOf(results.get('capital_social')).substring(3).remove('.').replace(',', '.')  ); Original code that received the field and sent it to the Account object 
            
    String cs=String.valueOf(results.get('capital_social')).substring(3).remove('.').replace(',', '.');
    cs=cs.replaceAll('[^0-9]', '');
    acc.Capital_Social__c = Decimal.valueOf(cs);
    System.debug('cs: '+ cs);
    System.debug('acc.Capital_Social__c: '+ acc.Capital_Social__c);

Do you know a better way to do this? A function or something else?

I don't know if the way I did it is working because I'm having trouble testing it, but I'm already seeing it with my supervisor, anyway I'd like to know what more experienced people have to say

Best Answer

Your solution will mangle decimals. You need to include the . character as well. Normally you would have to escape it, but in character sets it is already a literal. Feel free to test it for yourself with/without the . included.

You need:

cs = cs.replaceAll('[^0-9.]', '');

Please note that Regex 101 has an Explanation panel in its UI that tells you how this regular expression works.

  • /[^0-9.]/gm
    • Match a single character not present in the list below [^0-9.]
      • 0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
      • . matches the character . with index 4610 (2E16 or 568) literally (case sensitive)

It also has a helpful quick reference that explains various syntax.

  • [^abc] - a character except: a, b, or c
  • [^a-z] - a character not in the range: a-z

Putting it together, the recommended expression matches any character unless it is . (literal) or in the range 1-9. Note that it would match 1.2.3.4.5, so if you need more stringent validation you will need to go a more nuanced route.

Related Topic