black666 black666 - 9 months ago 43
Java Question

Get the Integer from the end of a string (variable length)

I have a string of a variable length and at the end of the string are some digits. What would be the best / efficient way, to parse the string and get the number from the end as an Integer?

The String and the digits at the end can can be of any length. For example:

abcd123 --> 123
abc12345 --> 12345
ab4cd1 --> 1

Answer Source

Something along the line of:

final static Pattern lastIntPattern = Pattern.compile("[^0-9]+([0-9]+)$");
String input = "...";
Matcher matcher = lastIntPattern.matcher(input);
if (matcher.find()) {
    String someNumberStr =;
    int lastNumberInt = Integer.parseInt(someNumberStr);

could do it.

This isn't necessary the "most efficient" way, but unless you have a critical bottleneck around this code (as: extract int from millions of String), this should be enough.