簡體   English   中英

python-re:我如何匹配alpha字符

[英]python-re: How do I match an alpha character

如何將alpha字符與正則表達式匹配。 我想要一個位於\\w但不在\\d的字符。 我希望它兼容unicode,這就是為什么我不能使用[a-zA-Z]

你的前兩句話相互矛盾。 “in \\w但不在\\d ”包括下划線。 我從你的第三句話中假設你不想要下划線。

在信封背面使用維恩圖有助於。 讓我們來看看我們不想要的東西:

(1)與\\w不匹配的字符(即不要求任何不是字母,數字或下划線的字符)=> \\W
(2)digits => \\d
(3)下划線=> _

所以我們不想要的是字符類[\\W\\d_]中的任何內容,因此我們想要的是字符類中的任何內容[^\\W\\d_]

這是一個簡單的例子(Python 2.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(杭州數字1)被視為數字(因此它匹配\\ w)但似乎Python將“數字”解釋為“十進制數字”(類別Nd),因此它與\\ d不匹配

U + 2438(圓形拉丁文小寫字母Y)與\\ w不匹配

所有CJK表意文字都被歸類為“字母”,因此匹配\\ w

無論上述3點中的任何一點是否值得關注,這種方法都是目前發布的最佳模塊。 將來會出現像\\ p {letter}這樣的語法。

關於什么:

\p{L}

您可以將此文檔用作參考: Unicode正則表達式

編輯:似乎Python不處理Unicode表達式 看看這個鏈接: 使用Python正則表達式處理重音字符 - [AZ]只是不夠好 (不再有效,鏈接到互聯網檔案)

另一個參考:


對於后代,以下是博客上的示例:

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éñ

您可以使用以下表達式之一來匹配單個字母:

(?![\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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM