使用 re.sub 替换多个字符

Wkh*_*han 5 python regex string python-2.7

s = "Bob hit a ball!, the hit BALL flew far after it was hit."
Run Code Online (Sandbox Code Playgroud)

我需要从 s 中删除以下字符

!?',;.
Run Code Online (Sandbox Code Playgroud)

如何使用 re.sub 来实现这一点?

re.sub(r"!|\?|'|,|;|."," ",s) #doesn't work. And replaces all characters with space
Run Code Online (Sandbox Code Playgroud)

有人能告诉我这有什么问题吗?

Tom*_*koo 10

问题是.匹配所有字符,而不是文字'.'。你也想逃避这个\.

但更好的方法是不使用 OR 运算符|,而是简单地使用字符组:

re.sub(r"[!?',;.]", ' ', s)
Run Code Online (Sandbox Code Playgroud)