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
Perhaps the easiest way of getting the number of digits in an Integer is by converting it to String, and calling the length() method. This will return the length of the String representation of our number: int length = String. valueOf(number).
The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).
To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string.
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.
Other solutions provided here are fine, so I'll provide this one just to be a bit different:
public static BigInteger lastBigInteger(String s) {
int i = s.length();
while (i > 0 && Character.isDigit(s.charAt(i - 1))) {
i--;
}
return new BigInteger(s.substring(i));
}
Character.isDigit(char)
BigInteger
, so it can handle really large numbers at the end of really long strings.
Integer.parseInt
or Long.parseLong
if either suffficeIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With