1

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.

4
  • 3
    string.replaceAll(".*\\D(\\d+).*", "$1"), demo Commented Jan 12, 2020 at 9:42
  • Is the pattern of your urls always ending with digits followed by non digits? Commented Jan 12, 2020 at 10:26
  • Yes, dryleaf, it is Commented Jan 12, 2020 at 10:52
  • See my answer below with a much enhanced solution version. Commented Jan 12, 2020 at 20:36

1 Answer 1

1

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 possible

The 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+).*|.+".

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the detailed answer, @Wiktor Stribiżew :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.