To get the number at the end of a string in Java, you can use the matches
method of the String
class and a regular expression to check if the string ends with a number, and the substring
method to extract the number.
Here is an example of how to get the number at the end of a string:
String str = "abc123"; if (str.matches(".*\\d$")) { int number = Integer.parseInt(str.substring(str.length() - 1)); // number will be 123 }Source:wwttual.wuri.com
The regular expression ".*\\d$"
matches any string that ends with a digit. The matches
method returns true
if the string matches the regular expression, and false
if it does not.
If the string ends with a number, we can use the substring
method to extract the number from the end of the string. The substring
method takes two arguments: the start index (inclusive) and the end index (exclusive) of the substring to be extracted. In this case, we use the length
method of the String
class to get the length of the string and subtract 1 to get the index of the last character. We then pass this index as the start index to the substring
method to extract the number.
Finally, we use the parseInt
method of the Integer
class to parse the extracted substring as an integer.
Note that this approach assumes that the number at the end of the string is a positive integer. If the number is negative or has a decimal point, you will need to use a different approach to extract and parse it.