Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract substring from end till first alphabet in java

I have a string of format: A-2-Q4567

More examples: AB-456-T12, A24-5-M12345, etc.

I want to extract the last numerical values out of these strings, which are: 4567, 12, 12345 respectively (which is the numerical value of the substring from the end till first non-numeric character is encountered)

I can split the string, get the last string from the splitted string array, and then do a parseInt after removing the non-numerical characters from it.

But is there a more elegant way of doing this?

like image 674
user1639485 Avatar asked Mar 25 '26 22:03

user1639485


1 Answers

You can use this regex: (\d+$). It returns the last sequence of digits in the string.

EDIT - some explanation:
The \d means any digit.
The + means one or more of the previous symbols. Since the previous symbol is a digit, then \d+ means "one or more digits".
The $ means the end of the string, so \d+$ is the last sequence of digits in the string.

like image 119
TDG Avatar answered Mar 27 '26 11:03

TDG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!