我試圖匹配這樣的字符串,我的表達式是^[0-9]+\s*\\x.{2}$
。它在pythex很好運作。但它在我的本地機器上不起作用。相同的正則表達式不適用於我的本地環境
In [223]: pattern = re.compile(r'^[0-9]+\s*\\x.{2}$')
In [224]: print re.match(pattern, "10\xbd")
None
我正在使用Python 2.7.10。謝謝!
我試圖匹配這樣的字符串,我的表達式是^[0-9]+\s*\\x.{2}$
。它在pythex很好運作。但它在我的本地機器上不起作用。相同的正則表達式不適用於我的本地環境
In [223]: pattern = re.compile(r'^[0-9]+\s*\\x.{2}$')
In [224]: print re.match(pattern, "10\xbd")
None
我正在使用Python 2.7.10。謝謝!
您的測試:
print re.match(pattern, "10\xbd")
的 「\ XBD」 正在interpretted一個特殊字符。您需要「轉義」它或使用原始字符串。
嘗試:
print re.match(pattern, r"10\xbd") # the r makes it a raw string
或
print re.match(pattern, "10\\xbd") # the extra \ 'escapes' the '\' so it is no longer special
也許你可以添加'r'(raw)並且他也可以逃脫一個char \\? – Alvaro
非常感謝!這個答案幫了很大忙。由於字符串來自我的情況,所以我需要'string = string.encode('string-escape')'來轉換它。同樣,在unicode情況下,它可以通過'string = string.encode('unicode-escape')'轉換。這[問題](http://stackoverflow.com/questions/2969044/python-string-escape-vs-unicode-escape)可以參考的細節。 –
如果輸入了文字''\'',那麼它的工作:「 」10 \\ XBD「'。請參閱[IDEONE演示](http://ideone.com/YKmUOZ)。 –
「10 \ xbd」是一個三字節字符串:1,0和'\ xbd'(它在ISO-8859和Unicode中是分數的1/2)。 – chepner
'\ xbd'是一個十六進制字符轉義序列。除非你的字符串前綴爲'r',就像你的正則表達式一樣,它不會被解析爲字符'\ xbd'。你的弦從哪裏來? – Blender