How to find all numbers in a string using Regex

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

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.


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