【问题标题】:Regular Expressions (regex) Remove the word "and", Non Alphanumeric Characters and White Spaces from a string in Python正则表达式 (regex) 从 Python 中的字符串中删除单词“and”、非字母数字字符和空格
【发布时间】:2021-03-07 13:37:20
【问题描述】:

在 Python 中,我正在尝试清理(以及稍后比较)艺术家姓名并希望删除:

  1. 非字母字符,或
  2. 空白,或
  3. “和”这个词

输入字符串: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 风格。这是为了避免熟悉其他语言的其他正则表达式风格的人误解这个问题是由拼写错误引起的,并认为它不可重现。

标签: python regex string


【解决方案1】:

为了支持您制定的规则,而不仅仅是引用的示例文本,您需要一个更通用的正则表达式,并为re.sub 调用设置正确的标志:

re.sub(r'\band\b|\W', '', s, flags=re.IGNORECASE)

说明

  • 设置了标志re.IGNORECASE,以便您还可以删除句子中的“And”(以及其他大写/小写组合变体)。如果您只想删除“and”而不是它的任何变体,您可以删除此标志设置。
  • \band\b 两边用单词边界标记\b 括起来的单词“and”。这是为了将 3 个字符序列“and”匹配为一个独立的单词,而不是另一个单词的子字符串。使用\b 来隔离单词而不是将单词包含在\s+and\s 之类的空格中,其优点是\b 选项还可以检测and, 之类的字符串中的单词边界,而\s+and\s 则不能。这是因为逗号不是空格。
  • 由于空格\s 也是一种非单词\W(因为单词\w 等同于[a-zA-Z0-9_]),所以两者不需要单独的正则表达式标记。 \W 已经包含 \s。因此,您可以简化正则表达式,而无需单独使用 \s

演示

测试用例 #1:

s = 'Bootsy Collins and The Rubber Band'
res = re.sub(r'\band\b|\W', '', s, flags=re.IGNORECASE)
print(res)

Output:
'BootsyCollinsTheRubberBand'

测试用例 #2('And' 被删除):

s = 'Bootsy Collins And The Rubber Band'
res = re.sub(r'\band\b|\W', '', s, flags=re.IGNORECASE)
print(res)

Output:
'BootsyCollinsTheRubberBand'

测试用例 #3('and,' [在 'and' 后加逗号] 被删除)

s = 'Bootsy Collins and, The Rubber Band'
res = re.sub(r'\band\b|\W', '', s, flags=re.IGNORECASE)
print(res)

Output:
'BootsyCollinsTheRubberBand'

反测试用例:(正则表达式使用空格 \s+\s 而不是 \b 作为单词边界)

s = 'Bootsy Collins and, The Rubber Band'
res = re.sub(r'\s+(and)\s|\W', '',s)
print(res)

Output:   'and' is NOT removed
'BootsyCollinsandTheRubberBand'            

【讨论】:

    【解决方案2】:

    您的前两个正则表达式不匹配“和”,因为当到达字符串中的那个位置时,正则表达式的\s 部分将匹配“and”之前的空格而不是\s+(and)\s 部分你的正则表达式。

    您只需更改顺序,以便先尝试后者。此外,\s[^\w] 的一部分,因此您无需单独匹配\s。最后,\W[^\w] 的缩写形式。所以使用:

    \s+(and)\s|\W 
    

    【讨论】:

      猜你喜欢
      • 2012-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 1970-01-01
      • 2012-06-22
      • 2018-11-20
      相关资源
      最近更新 更多