totothegreat totothegreat - 1 month ago 6
Java Question

How to extract last digits in a string in java?

I have a string like so:
"i am 12 and i want 15 blah blah"
i want to extract only the last instance of digits using regex in java, i can extract all of them like so:

Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(msg);
if (m.find()) {
System.out.print("Start index: " + m.start());
System.out.print(" End index: " + m.end());
System.out.println(" Found: " + m.group());
}


and the last interval will be it, but there must be simple way to do so, is it something to do with $ ?

Jan Jan
Answer

You could use

(\d+)\D*$

See a demo on regex101.com.
Note, that you need to double escape the expression in Java, so that it becomes:

(\\d+)\\D*$