我遇到的情况是我有一个字符串和一个连续重复的特殊符号,例如:
s = 'a.b.c...d..e.g'
Run Code Online (Sandbox Code Playgroud)
如何检查是否重复并删除连续符号,结果如下:
s = 'a.b.c.d.e.g'
Run Code Online (Sandbox Code Playgroud)
import re
result = re.sub(r'\.{2,}', '.', 'a.b.c...d..e.g')
Run Code Online (Sandbox Code Playgroud)
更通用的版本:
import re
symbol = '.'
regex_pattern_to_replace = re.escape(symbol)+'{2,}'
# Note that escape sequences are processed in replace_to
# but this time we have no backslash characters in it.
# In case of more complex replacement we could use
# replace_to = replace_to.replace('\\', '\\\\')
# to defend against occasional escape sequences.
replace_to = symbol
result = re.sub(regex_pattern_to_replace, replace_to, 'a.b.c...d..e.g')
Run Code Online (Sandbox Code Playgroud)
与编译的正则表达式相同(在Cristian Ciupitu的评论之后添加):
compiled_regex = re.compile(regex_pattern_to_replace)
# You can store the compiled_regex and reuse it multiple times.
result = compiled_regex.sub(replace_to, 'a.b.c...d..e.g')
Run Code Online (Sandbox Code Playgroud)
查看re.sub的文档