regex: eliminate all numbers between slashes

Viewed 60

Expected: http://some_url.com/api/v1/1/2/3/4" -> http://some_url.com/api/v1/*/*/*/*/ What I use:

re.sub(r"/\d+/?", "/*/", str(url), flags=re.IGNORECASE)

Actual: http://some_url.com/api/v1/*/2/*/4/

2 Answers

You may use

/\d+(?=/|$)
/\d+(?![^/])

and replace with /*. See the regex demo.

In Python:

url = re.sub(r"/\d+(?=/|$)", "/*", url)

Details

  • / - a / char
  • \d+ - 1+ digits
  • (?![^/]) - a negative lookahead that fails the match if the next char is not a character other than / (so, end of string or / are required immediately to the right of the current location, same as with the positive (?=/|$) lookahead)

See Python demo online:

import re
url = 'http://some_url.com/api/v1/1/2/3/4'
url = re.sub(r"/\d+(?=/|$)", "/*", url)
print(url)
# => http://some_url.com/api/v1/*/*/*/*
Related