Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何替换单个斜杠'/';在不包括';中斜杠字符的字符串中://';图案_Python_Regex_Substitution - Fatal编程技术网

Python 如何替换单个斜杠'/';在不包括';中斜杠字符的字符串中://';图案

Python 如何替换单个斜杠'/';在不包括';中斜杠字符的字符串中://';图案,python,regex,substitution,Python,Regex,Substitution,我试图找到一种方法来替换字符串中的单个斜杠字符“/”,除了“https://”中的斜杠或“http://”中的斜杠 a="https://example.com/example/page/" 例如,我想将“/”替换为“%”,但不替换“https://”中的斜杠字符或“http://”中的斜杠字符,以便在最后得到如下结果: a="https://example.com%example%page%" 我试过了 re.sub('(?<!:\/)\/', '%', a) re.sub(”(?

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

a="https://example.com/example/page/"
例如,我想将“/”替换为“%”,但不替换“https://”中的斜杠字符或“http://”中的斜杠字符,以便在最后得到如下结果:

a="https://example.com%example%page%"
我试过了

re.sub('(?<!:\/)\/', '%', a)
re.sub(”(?您可以使用

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

  • (https?| ftps?)://
    -匹配并捕获到组1
    http
    /
    https
    /
    ftp
    /
    ftps
    (如果需要,添加更多),然后匹配
    :///code>
  • |
    -或
  • /
    -匹配任何其他上下文中的
    /
如果组1匹配,则将整个匹配粘贴回,否则,
/
将替换为
%

见:


http是一个示例设备。
/
文件根目录也是。
/
文件根目录也有很多标准设备/协议等。您最好将所有设备/协议都保留下来,然后匹配一个/。您可以使用
(?)?
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%