【问题标题】:Python regex with unicode strings带有 unicode 字符串的 Python 正则表达式
【发布时间】:2015-03-30 16:18:03
【问题描述】:

在 python 2.7 中无法匹配 unicode 字符串。 预期结果 749130

>>> print match("\d+", u'\ufeff749130'.encode('utf-8'))
None
>>> print match("\d+", u'\ufeff749130')
None
>>> print match("\d+", u'\ufeff749130'.decode('utf-8'))
Traceback (most recent call last):
....
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 0: ordinal not in range(128)

【问题讨论】:

  • match 从字符串的开头匹配。使用search
  • 请为您的问题添加更多详细信息。想用代码做什么?

标签: python regex unicode


【解决方案1】:

无需在 unicode 字符串上使用 str.decode。如 cmets 中所述,您可能希望使用 search,因为 match 仅匹配目标字符串的开头。

>>> print search("\d+", u'\ufeff749130').group()
749130

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 1970-01-01
    • 2010-09-28
    • 2012-03-24
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2017-04-26
    相关资源
    最近更新 更多