簡體   English   中英

Python re和regex:search()與非ASCII字符的相同字符串不匹配

[英]Python re and regex: search() doesn't doesn't match identical strings with non-ASCII characters

嘗試獲取re或regex使其自身與非ASCII字符串匹配。 我已經閱讀了有關非ASCII / unicode的其他文章,並嘗試添加unicode標志,但無濟於事:

# python
Python 2.7.3 (default, Apr 14 2012, 08:58:41) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> import regex
>>> s1 = 'wow'
>>> s2 = 'ℛℯα∂α♭ℓℯ ♭ʊ☂ η☺т Ѧ$☾ℐℐ'
>>> print(s2)
ℛℯα∂α♭ℓℯ ♭ʊ☂ η☺т Ѧ$☾ℐℐ
>>> re.search(s1,s1)
<_sre.SRE_Match object at 0x7f0ce27c38b8>
>>> re.search(s2,s2)
>>> type(s2)
<type 'str'>
>>> us2 = unicode(s2,'utf-8')
>>> us2
u'\u211b\u212f\u03b1\u2202\u03b1\u266d\u2113\u212f \u266d\u028a\u2602 \u03b7\u263a\u0442 \u0466$\u263e\u2110\u2110'
>>> re.search(us2,us2,re.UNICODE)
>>> regex.search(s2,s2)
>>> regex.search(us2,us2,regex.UNICODE)
>>>   

我希望我缺少明顯的東西。 任何幫助,不勝感激!

注意,作為正則表達式模式, s2內部具有at at_end模式。

In [62]: re.compile(s2, re.DEBUG)
literal 226
literal 132
literal 155
...
at at_end
...
literal 226
literal 132
literal 144

這是因為,作為utf-8編碼的字符串, s2

In [61]: s2 = 'ℛℯα∂α♭ℓℯ ♭ʊ☂ η☺т Ѧ$☾ℐℐ'
In [72]: s2
Out[72]: '\xe2\x84\x9b\xe2\x84\xaf\xce\xb1\xe2\x88\x82\xce\xb1\xe2\x99\xad\xe2\x84\x93\xe2\x84\xaf \xe2\x99\xad\xca\x8a\xe2\x98\x82 \xce\xb7\xe2\x98\xba\xd1\x82 \xd1\xa6$\xe2\x98\xbe\xe2\x84\x90\xe2\x84\x90'

並注意s2有一個$

In [75]: '$' in s2
Out[75]: True

為了防止將$解釋為at at_end模式,請使用re.escape來轉義該模式中的所有非字母數字字符:

In [67]: pat = re.compile(re.escape(s2))

In [68]: pat.search(s2)
Out[68]: <_sre.SRE_Match at 0x7feb6b44dd98>

轉義unicode模式也是如此:

In [78]: us2 = unicode(s2,'utf-8')

In [79]: re.search(re.escape(us2), us2)
Out[79]: <_sre.SRE_Match at 0x7feb6b44ded0>

以來

In [81]: u'$' in us2
Out[81]: True

暫無
暫無

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

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