Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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
like image 793
black666 Avatar asked Apr 12 '10 08:04

black666


People also ask

How do you find the length of an int variable?

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).

How do you find a number in a string?

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+)/).

How do you only extract a number from a string in Python?

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.


2 Answers

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.

like image 185
VonC Avatar answered Oct 13 '22 06:10

VonC


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));
}
  • It manually looks for the position of the last non-Character.isDigit(char)
    • It still works if the input is all digit
  • It uses BigInteger, so it can handle really large numbers at the end of really long strings.
    • Use Integer.parseInt or Long.parseLong if either sufffice
like image 21
polygenelubricants Avatar answered Oct 13 '22 07:10

polygenelubricants