如何将字母字符与正则表达式匹配。我想要一个字符是在\w中,但不在\d中。我想让它兼容unicode,这就是我不能使用[a-zA-Z]的原因。
发布于 2010-01-11 09:41:49
你的前两句话相互矛盾。"in \w但is not in \d“包括下划线。我从你的第三句话中假设你不想下划线。
使用信封背面的维恩图会有所帮助。让我们看看我们不想要的东西:
(1) \w不匹配的字符(即不需要任何不是字母、数字或下划线的字符) => \W
(2) digits => \d
(3)下划线=> _
因此,我们不需要字符类[\W\d_]中的任何内容,因此我们需要字符类[^\W\d_]中的任何内容
这里有一个简单的例子(Python2.6)。
>>> import re
>>> rx = re.compile("[^\W\d_]+", re.UNICODE)
>>> rx.findall(u"abc_def,k9")
[u'abc', u'def', u'k']进一步的探索揭示了这种方法的一些怪癖:
>>> import unicodedata as ucd
>>> allsorts =u"\u0473\u0660\u06c9\u24e8\u4e0a\u3020\u3021"
>>> for x in allsorts:
... print repr(x), ucd.category(x), ucd.name(x)
...
u'\u0473' Ll CYRILLIC SMALL LETTER FITA
u'\u0660' Nd ARABIC-INDIC DIGIT ZERO
u'\u06c9' Lo ARABIC LETTER KIRGHIZ YU
u'\u24e8' So CIRCLED LATIN SMALL LETTER Y
u'\u4e0a' Lo CJK UNIFIED IDEOGRAPH-4E0A
u'\u3020' So POSTAL MARK FACE
u'\u3021' Nl HANGZHOU NUMERAL ONE
>>> rx.findall(allsorts)
[u'\u0473', u'\u06c9', u'\u4e0a', u'\u3021']U+3021 (杭州数字一)被视为数字(因此它与\w匹配),但是Python似乎将“数字”解释为“十进制数字”(类别Nd),因此它与\d不匹配
U+2438 (带圆圈的拉丁文小写字母Y)不匹配\w
所有CJK表意文字都被归类为“字母”,因此匹配\w
无论以上3点是否值得关注,这种方法都是您从当前发布的re模块中获得的最佳方法。像\p{letter}这样的语法是未来的趋势。
发布于 2010-01-11 07:45:56
下面是什么:
\p{L}您可以使用此文档作为参考:Unicode Regular Expressions
编辑:似乎是Python doesn't handle Unicode expressions。看看这个链接:Handling Accented Characters with Python Regular Expressions -- [A-Z] just isn't good enough (不再活跃,链接到互联网档案)
另一个参考文献:
对于后人,这里有博客上的例子:
import re
string = 'riché'
print string
riché
richre = re.compile('([A-z]+)')
match = richre.match(string)
print match.groups()
('rich',)
richre = re.compile('(\w+)',re.LOCALE)
match = richre.match(string)
print match.groups()
('rich',)
richre = re.compile('([é\w]+)')
match = richre.match(string)
print match.groups()
('rich\xe9',)
richre = re.compile('([\xe9\w]+)')
match = richre.match(string)
print match.groups()
('rich\xe9',)
richre = re.compile('([\xe9-\xf8\w]+)')
match = richre.match(string)
print match.groups()
('rich\xe9',)
string = 'richéñ'
match = richre.match(string)
print match.groups()
('rich\xe9\xf1',)
richre = re.compile('([\u00E9-\u00F8\w]+)')
print match.groups()
('rich\xe9\xf1',)
matched = match.group(1)
print matched
richéñ发布于 2016-03-04 00:04:41
您可以使用以下表达式之一来匹配单个字母:
(?![\d_])\w或
\w(?<![\d_])在这里我匹配\w,但在此之前/之后检查[\d_]是否不匹配。
从文档中:
(?!...)
Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.
(?<!...)
Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length and shouldn’t contain group references. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.https://stackoverflow.com/questions/2039140
复制相似问题