How to extract all the numbers from a string include start and end index using regex in Java

1 Answer

0 votes
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class MyClass {
    public static void main(String args[]) {
        String s = "java01223c++3php500--9_8";  
        String regex = "[0-9]+";            

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(s);

        while (matcher.find()) {
            System.out.println(matcher.group() + 
                               " - index from: " + 
                               matcher.start() + " to: " + matcher.end());
      }
    }
}



/*
run:

01223 - index from: 4 to: 9
3 - index from: 12 to: 13
500 - index from: 16 to: 19
9 - index from: 21 to: 22
8 - index from: 23 to: 24

*/

 



answered Aug 1, 2019 by avibootz
...