【发布时间】: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