Reputation: 103
I have some URL link and tried to replace all non-integer values with integers in the end of the link using regex
The URL is something like
https://some.storage.com/test123456.bucket.com/folder/80.png
Regex i tried to use:
Integer.parseInt(string.replaceAll(".*[^\\d](\\d+)", "$1"))
Output for that regex is "80.png", and i need only "80". Also i tried this tool - https://regex101.com. And as i see the main problem is that ".png" not matching with my regex and then, after substitution, this part adding to matching group.
I'm totally noob in regex, so i kindly ask you for help.
Upvotes: 1
Views: 233
Reputation: 627410
You may use
String result = string.replaceAll("(?:.*\\D)?(\\d+).*", "$1");
See the regex demo.
NOTE: If there is no match, the result
will be equal to the string
value. If you do not want this behavior, instead of "(?:.*\\D)?(\\d+).*"
, use "(?:.*\\D)?(\\d+).*|.+"
.
Details
(?:.*\D)?
- an optional (it must be optional because the Group 1 pattern might also be matched at the start of the string) sequence of
.*
- any 0+ chars other than line break chars, as many as possible\D
- a non-digit(\d+)
- Group 1: any one or more digits.*
- any 0+ chars other than line break chars, as many as possibleThe replacement is $1
, the backreference to Group 1 value, actually, the last 1+ digit chunk in the string that has no line breaks.
Line breaks can be supported if you prepend the pattern with the (?s)
inline DOTALL modifier, i.e. "(?s)(?:.*\\D)?(\\d+).*|.+"
.
Upvotes: 1