使用正则表达式删除撇号 u+2019 以外的特殊符号

Remove special symbols except apostrophes u+2019 using Regex

根据用户输入,我有一串包含特殊 unicode 字符的名称。我正在使用 Python 2.7。

例如:

Panzdella*, Meslone‡, Pezzeella, Rossssi, Pastooori, Perfeetti, D’Erriico†, Puunta*, and d’Ischaia. 

我想删除除 * 和弯撇号 (’) 之外的所有特殊字符。

这是我正在做的事情:

import re

authors = raw_input('enter authors to clean characters: ')

# old code authors = re.sub(r'[^a-zA-Z0-9 - \,\*-\u2019]', '', authors)

#new suggestion
authors = re.sub(r'[^a-zA-Z0-9 ,*\u2019-]', '', authors)
print authors

结果不保留弯撇号 ’(u+2019)。

如何使用正则表达式提供弯撇号异常?

您可以使用:

authors  = re.sub(ur'[^a-zA-Z0-9 ,*\u2019-]', '', authors)

确保在字符 class 的最后或第一个位置保留连字符。

输出:

Panzdella*, Meslone, Pezzeella, Rossssi, Pastooori, Perfeetti, D’Erriico, Puunta*, and d’Ischaia

示例代码:

import sys, locale, re

authors = raw_input().decode(sys.stdin.encoding or locale.getpreferredencoding(True))

print re.sub(ur'[^a-zA-Z0-9 ,*\u2019-]', '', authors)

关于您使用的先前模式的一些注释:

  • space + - + space 刚好匹配 space 因为连字符创建的范围从 space 到 space
  • *-\uXXX 也试图建立一个范围,但这不是你想要的。

为避免字符 class 中的文字连字符出现问题,请将它们放在开头或结尾:

[^a-zA-Z0-9 ,*\u2019-]

现在,由于您使用的是 Python 2.7,字符串在那里是字节数组,为了使用 Unicode,它们总是必须转换 (en/decoded) to/from UTF8.

这里有一个方法可以让它工作:

# -*- coding: utf-8 -*-
import re
authors = "Panzdella*, Meslone‡, Pezzeella, Rossssi, Pastooori, Perfeetti, D’Erriico†, Puunta*, and d’Ischaia."
authors = re.sub(ur'[^a-zA-Z0-9 ,*\u2019-]', u'', authors.decode('utf8'), 0, re.UNICODE).encode("utf8")
print authors

IDEONE demo

输出:Panzdella*, Meslone, Pezzeella, Rossssi, Pastooori, Perfeetti, D’Erriico, Puunta*, and d’Ischaia