Reputation: 45
I am trying to find a way to replace single slash character '/' from a string except the slashes in 'https://' or not in 'http://'
a="https://example.com/example/page/"
I would like to substitute '/' for example with '%' but not the slash characters in 'https://' or not in 'http://' so that at the end I have the result like:
a="https://example.com%example%page%"
I tried
re.sub('(?<!:\/)\/', '%', a)
in python but it is not correct.
Upvotes: 2
Views: 62
Reputation: 626758
You may use
re.sub(r'(https?|ftps?)://|/', lambda x: x.group(0) if x.group(1) else '%', s)
Details
(https?|ftps?)://
- matches and captures into Group 1 http
/https
/ftp
/ftps
(add more if needed) and then matches ://
|
- or/
- matches /
in any other contextIf Group 1 is matched, the whole match is pasted back, else, the /
is replaced with %
.
See the Python demo:
import re
s = 'https://example.com/example/page/'
print(re.sub(r'(https?|ftps?)://|/', lambda x: x.group(0) if x.group(1) else '%', s))
# => https://example.com%example%page%
Upvotes: 2