我有这样的文本:
the quick brown fox ?? m i c r o s o f t ? ? ? ? ? ? ? jumps over the lazy dog ???? best wishes : John Doe
Run Code Online (Sandbox Code Playgroud)
什么是好的正则表达式(对于python)可以删除单个字符,以便输出如下所示:
the quick brown fox ?? jumps over the lazy dog ???? best wishes John Doe
Run Code Online (Sandbox Code Playgroud)
我尝试了 的一些组合\s{1}\S{1}\s{1}\S{1},但它们最终不可避免地删除了比我需要的更多的字母。
非正则表达式版本可能如下所示:
source_string = r"this is a string I created"
modified_string =' '.join([x for x in source_string.split() if len(x)>1])
print(modified_string)
Run Code Online (Sandbox Code Playgroud)
您可以将以下内容替换为空字符串:
(?<!\S)\S(?!\S).?
Run Code Online (Sandbox Code Playgroud)
匹配两边都没有非空格的非空格(即被空格包围),加上其后的字符(如果有)。
我使用否定查找的原因是因为它可以巧妙地处理字符串大小写的开始/结束。我们匹配 后面的额外字符\S来删除空格。