totothegreat totothegreat - 1 year ago 158
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: " +;

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 Source

You could use


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download