How to find all numbers in a string using Regex

  • I am trying to extract all numbers from a string but I got the below code to work although it stops after the first match for 123.

    String str = '123-456/7890';
    Pattern p = Pattern.compile('(\\d+)');
    Matcher m = p.matcher( str );
    
    if( m.find() ){
        system.debug( '-->>' + m.group() );
    }
    
  • You need to call matcher.find() recursively until it returns false. Use a do/while block.

    String str = '123-456/7890';
    Pattern p = Pattern.compile('(\\d+)');
    Matcher m = p.matcher( str );
    
    if(m.find()) {
      do {
        system.debug( '-->>' + m.group() );
      } while(m.find());
    }
    

    You can put while at the start, which avoids the need for if: `while(m.find()) { system.debug('-->>'+m.group()); }`

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM