【发布时间】:2021-03-07 13:37:20
【问题描述】:
在 Python 中,我正在尝试清理(以及稍后比较)艺术家姓名并希望删除:
- 非字母字符,或
- 空白,或
- “和”这个词
输入字符串:Bootsy Collins and The Rubber Band
期望的输出:BootsyCollinsTheRubberBand
import re
s = 'Bootsy Collins and The Rubber Band'
res1 = re.sub(r'[^\w]|\s|\s+(and)\s', "", s)
res2 = re.sub(r'[^\w]|\s|\sand\s', "", s)
res3 = re.sub(r'[^\w]|\s|(and)', "", s)
print("\b", s, "\n"
, "1st: ", res1, "\n"
, "2nd: ", res2, "\n"
, "3rd: ", res3)
Output:
Bootsy Collins and The Rubber Band
1st: BootsyCollinsandTheRubberBand
2nd: BootsyCollinsandTheRubberBand
3rd: BootsyCollinsTheRubberB
【问题讨论】:
-
此处答案提供的解决方案正则表达式也适用于其他正则表达式风格/品种(例如 PCRE、ECMAScript、Golang、java)。但是,标题和问题内容已添加了所使用语法的特定 Python 风格。这是为了避免熟悉其他语言的其他正则表达式风格的人误解这个问题是由拼写错误引起的,并认为它不可重现。