Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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() );
}
share|improve this question

3 Answers 3

up vote 0 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(matcher.find()) {
  do {
    system.debug( '-->>' + m.group() );
  } while(matcher.find());
}
share|improve this answer
    
Thanks. This works –  HSG Jul 26 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,

Reference:

http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum

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

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

Your Answer

 
discard

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.