Java Regex to replace only part of string (url)

Garbage :

I want to replace only numeric section of a string. Most of the cases it's either full URL or part of URL, but it can be just a normal string as well.

  • /users/12345 becomes /users/XXXXX
  • /users/234567/summary becomes /users/XXXXXX/summary
  • /api/v1/summary/5678 becomes /api/v1/summary/XXXX
  • http://example.com/api/v1/summary/5678/single becomes http://example.com/api/v1/summary/XXXX/single

Notice that I am not replacing 1 from /api/v1

So far, I have only following which seem to work in most of the cases:

input.replaceAll("/[\\d]+$", "/XXXXX").replaceAll("/[\\d]+/", "/XXXXX/");

But this has 2 problems:

  • The replacement size doesn't match with the original string length.
  • The replacement character is hardcoded.

Is there a better way to do this?

anubhava :

In Java you can use:

str = str.replaceAll("(/|(?!^)\\G)\\d(?=\\d*(?:/|$))", "$1X");

RegEx Demo

RegEx Details:

  • \G asserts position at the end of the previous match or the start of the string for the first match.
  • (/|(?!^)\\G): Match / or end of the previous match (but not at start) in capture group #1
  • \\d: Match a digit
  • (?=\\d*(?:/|$)): Ensure that digits are followed by a / or end.
  • Replacement: $1X: replace it with capture group #1 followed by X

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=295345&siteId=1