【问题标题】:How to write regular expression matching all unicode characters in Python? [duplicate]如何在 Python 中编写匹配所有 unicode 字符的正则表达式? [复制]
【发布时间】:2015-05-01 07:04:18
【问题描述】:

我之前读过documentation,写了数百个正则表达式,但我不知道如何检测unicode letter的序列。

# this will detect sequence of English letters
re.compile(r'[a-zA-Z]+')
# this will detect sequence of Unicode letters + [0-9_]
re.compile(r'\w+', re.UNICODE)
# how to detect sequence only unicode letter (without [0-9_])
re.compile(r'????', re.UNICODE)

如何只匹配unicode字符而不匹配[0-9_]?


我测试了你的解决方案:

import re
import timeit

def test1():
  regex = re.compile(ur'(?:(?![\d_])\w)+', re.UNICODE)
  return regex.findall(u'Ala ma kota z czarną sierścią - 1halo - halo1.')

def test2():
  regex = re.compile(ur'[^\W\d_]+', re.UNICODE)
  return regex.findall(u'Ala ma kota z czarną sierścią - 1halo - halo1.')

print test1()
print test2()

print timeit.timeit(test1)
print timeit.timeit(test2)

时间是:

[u'Ala', u'ma', u'kota', u'z', u'czarn\u0105', u'sier\u015bci\u0105', u'halo', u'halo']
[u'Ala', u'ma', u'kota', u'z', u'czarn\u0105', u'sier\u015bci\u0105', u'halo', u'halo']
11.0143377108
7.42619199741

【问题讨论】:

  • 你对“Unicode 字符”的定义是什么? “Unicode”涵盖了所有个属于 Unicode 规范的字符。
  • 也许是re.compile(r'[^0-9_]',re.UNICODE)
  • 您必须自己找到所需字符的所有范围。
  • 您的意思是要匹配除标准拉丁字符 A-Z 和标准数字 0-9 之外的所有单词字符(用于组成任何语言的单词)?标点符号呢?空白?控制字符?符号字符(如数学符号)?你越清楚你的要求,你就越有可能得到一个好的答案。
  • @Aaron [^0-9_] 也不是字母而是空格 - 失败。

标签: python regex python-2.7


【解决方案1】:

您可以将负前瞻与\w 结合使用以匹配不包括数字和下划线的“单词字符”:

re.compile(r"(?:(?![\d_])\w)+", re.UNICODE)

【讨论】:

  • 失败>>> re.findall(r'(?:(?![\d_])\w)+', 'Ala ma kota z czarną sierścią.', re.UNICODE) == ['Ala', 'ma', 'kota', 'z', 'czarn\xb9', 'sier', 'ci\xb9']
  • 我怀疑这是您的字符串的编码问题。它适用于我使用 Python 3。如果您使用的是 Python 2,请尝试在字符串的引号之前放置 u 以使其成为 Unicode 文字。
【解决方案2】:

使用 Unicode 字符串和源编码,然后查找您在评论中指定的字符。 Python 2.7 没有“Unicode 字母字符”的快捷方式:

# coding: utf8
import re
expr = re.compile(ur'(?u)[^\W\d_]+')
s = u'The quick brown fóx jumped over Łhe laży dog 17 times.'
for i in expr.finditer(s):
    print i.group(0)

输出:

The
quick
brown
fóx
jumped
over
Łhe
laży
dog
times

如果您想了解所有 Unicode 认为的大写和小写 Unicode 字母,另请参阅 this answer

【讨论】:

  • 您的解决方案不是很好的模式,因为它仅适用于波兰语 - 我认为[^\W\d_] 更好,但需要测试或(?:(?![\d_])\w)+
  • @Chameleon,另请参阅完整解决方案的链接答案。
  • @Chameleon, [^\W\d_] 如果您添加 Unicode 标志,则可以使用。查看更新,但请确保使用 Unicode 字符串。
  • 我一直使用 unicode,因为我在做使用波兰语、德语和英语的全球程序。
【解决方案3】:

试试这个 这匹配任何没有数字的 unicode 字符

re.compile(r'\D')

【讨论】:

  • 这也会包含空格和符号,并且需要 re.UNICODE 标志。
  • 失败。也匹配空格。
猜你喜欢
  • 2021-09-26
  • 1970-01-01
  • 2021-10-16
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 2017-01-24
  • 2011-03-08
相关资源
最近更新 更多