6

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() );
}

4 Answers 4

7

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());
}
1
  • 1
    You can put while at the start, which avoids the need for if: while(m.find()) { system.debug('-->>'+m.group()); }
    – sfdcfox
    Feb 3, 2017 at 0:03
6

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.

4

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

Reference:

https://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

2
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

System.debug(numericOutput);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .