re.sub()不会替代所有出现,但是re.findall()正在获取所有出现

问题描述 投票:0回答:2

我在python中有一个字符串,其中包含符号和字母数字字符。如果in字符串的两个字母数字字符之间有符号或空格,那么我想将它们替换为一个空格,“以提高可读性”。

注意:re.findall()返回所有子字符串,但re.sub()不能替换所有子字符串。

输入:-

#It#%%is$Matrix%%$script$Trinity

预期输出:-

#It is Matrix script Trinity

我已经尝试过下面的代码,但是它给出了预期的输出,任何python / regex专家都可以提供帮助?

import re
b= "#It#%%is$Matrix%%$script$Trinity"

print(re.findall(r'(?<=\w)(\W+)(?=\w)',b,re.IGNORECASE))
['#%%', '$', '%%$', '$']

print(re.sub(r'(?<=\w)(\W+)(?=\w)'," ",b,re.IGNORECASE))
#It is Matrix%%$script$Trinity

python regex python-3.x substitution findall
2个回答
2
投票
re.findall(pattern, string, flags=0) re.sub(pattern, repl, string, count=0, flags=0)

1
投票

-1
投票
© www.soinside.com 2019 - 2024. All rights reserved.