I am trying to remove some predefined consecutive punctuation marks and replace them with the first. Thus:
I tried the following code:
import re
r = re.compile(r'([.,/#!$%^&*;:{}=-_`~()])*\1')
n = r.sub(r'\1', "ews by almalki : Tornado, flood deaths reach 18 in U.s., more storms ahead ")
print(n)
Run Code Online (Sandbox Code Playgroud)
您只需要捕获第一个标点符号并匹配其余的:
([.,/#!$%^&*;:{}=_`~()-])[.,/#!$%^&*;:{}=_`~()-]+
Run Code Online (Sandbox Code Playgroud)
请注意,-必须将放在字符类的末尾(或开始),以免创建范围(否则可以在字符类内部转义)。
详细资料:
([.,/#!$%^&*;:{}=_`~()-]) -使用您定义的标点符号捕获组[.,/#!$%^&*;:{}=_`~()-]+ -1+个标点符号 import re
r = re.compile(r'([.,/#!$%^&*;:{}=_`~()-])[.,/#!$%^&*;:{}=_`~()-]+')
n = r.sub(r'\1', "ews by almalki : Tornado, flood deaths reach 18 in U.s., more storms ahead ")
print(n)
Run Code Online (Sandbox Code Playgroud)