如何替换字符串中的单个斜杠“/”,不包括“://”模式中的斜杠字符

How to replace a single slash '/' in a string excluding the slash characters in the '://' pattern

我正在尝试找到一种方法来替换字符串中的单斜杠字符“/”,除了 'https://' 中的斜杠或 'http://'

中的斜杠除外
a="https://example.com/example/page/"

例如,我想用“%”代替“/”,而不是 'https://' 中的斜线字符或 'http://' 中的斜线字符,这样最后我得到的结果如下:

a="https://example.com%example%page%"

我试过了

re.sub('(?<!:\/)\/', '%', a)

在 python 但不正确。

您可以使用

re.sub(r'(https?|ftps?)://|/', lambda x: x.group(0) if x.group(1) else '%', s)

详情

  • (https?|ftps?):// - 匹配并捕获到第 1 组 http/https/ftp/ftps(如果需要添加更多),然后匹配 ://
  • | - 或
  • / - 在任何其他上下文中匹配 /

如果第 1 组匹配,则将整个匹配粘贴回去,否则,/ 将替换为 %

参见 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%