Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
95 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 = matcher.group(1);
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...