python - Python 中的正则表达式和 Unicode : difference between sub and findall

标签 python regex unicode

我很难找出我的 Python (2.7) 脚本中的错误。我在识别特殊字符时使用 sub 和 findall 有所不同。

代码如下:

>>> re.sub(ur"[^-' ().,\w]+", '' , u'Castañeda', re.UNICODE)
u'Castaeda'
>>> re.findall(ur"[^-' ().,\w]+", u'Castañeda', re.UNICODE)
[]

当我使用 findall 时,它正确地将 ñ 视为字母字符,但当我使用 sub 时,它会替换它——将其视为非字母字符。

我已经能够使用带有 string.replace 的 findall 获得正确的功能,但这似乎是一个糟糕的解决方案。另外,我想使用 re.split,但遇到了与 re.sub 相同的问题。

在此先感谢您的帮助。

最佳答案

re.sub 的调用签名是:

re.sub(pattern, repl, string, count=0)

所以

re.sub(ur"[^-' ().,\w]+", '' , u'Castañeda', re.UNICODE)

正在将 count 设置为 re.UNICODE,其值为 32。

改为尝试:

In [57]: re.sub(ur"(?u)[^-' ().,\w]+", '', u'Castañeda')
Out[57]: u'Casta\xf1eda'

(?u) 放在正则表达式的开头是在正则表达式本身中指定 re.UNICODE 标志的另一种方法。您还可以设置其他标志 (?iLmsux) 这样。 (有关更多信息,请单击 this link 并搜索“(?iLmsux)”。)

同理,re.split的调用签名为:

re.split(pattern, string, maxsplit=0)

解决方法是一样的。

关于python - Python 中的正则表达式和 Unicode : difference between sub and findall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6309387/

相关文章:

javascript - 为什么此代码显示不正确的 Unicode?

python - 如何为正则表达式转义 unicode 字符串?

regex - 为什么 Perl 正则表达式挂起?

python - 正则表达式 Python [python-2.7]

regex - 如何否定正则表达式中的字符串

python - 在 Django 表单中组合 ModelChoiceField 以保存在单个 ManyToManyField 中

c - Linux 上 UTF-16 的 wchar_t?

Python解析器模块教程

python - 在Python中如何查看一个列表是否包含另一个列表?

python - 使用 Flask 将表单中的输入行作为对象发布?