Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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( '-->>' + );
share|improve this question
up vote 2 down vote accepted

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( '-->>' + );
  } while(m.find());
share|improve this answer
Thanks. This works – HSG Jul 26 '14 at 12:21

If you want to separate all the numbers into separate strings you can do the following.

String numsplit = str.replaceAll('[^0-9]+', ';');
list<String> nums = numsplit.split(';');

If you also want to extract the other characters there is a built-in splitbycharactertype method.

share|improve this answer

You can use the Regex (?!^), this is called negative look ahead,


string abc = '123abc224aa33//11``45345';
string newstringwithjustnumbers='';
for(string s : abc.split('(?!^)')){
        newstringwithjustnumbers = newstringwithjustnumbers+s;

Debug Log output :

10:45:01.244 (244625510)|SYSTEM_METHOD_ENTRY|[9]|System.debug(ANY) 10:45:01.244 (244660455)|USER_DEBUG|[9]|DEBUG|@@@@@123224331145345

share|improve this answer
String input  = String.valueOf('20.02.001.X-M,!');

Pattern p = Pattern.compile('[^0-9]');

String numericOutput = p.matcher(input).replaceAll('');

//debug statement below will print 2002001

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.