[英]Writing unicode regex for both Python2 and Python3
我可以在 Python2 中使用ur'something'
和re.U
標志來編譯正則表達式模式,例如:
$ python2
Python 2.7.13 (default, Dec 18 2016, 07:03:39)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> pattern = re.compile(ur'(«)', re.U)
>>> s = u'«abc «def«'
>>> re.sub(pattern, r' \1 ', s)
u' \xab abc \xab def \xab '
>>> print re.sub(pattern, r' \1 ', s)
« abc « def «
在 Python3 中,我可以避免使用u'something'
甚至re.U
標志:
$ python3
Python 3.5.2 (default, Oct 11 2016, 04:59:56)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> pattern = re.compile(r'(«)')
>>> s = u'«abc «def«'
>>> print( re.sub(pattern, r' \1 ', s))
« abc « def «
但目標是編寫正則表達式,使其同時支持 Python2 和 Python3。 在 Python3 中執行ur'something'
會導致語法錯誤:
>>> pattern = re.compile(ur'(«)', re.U)
File "<stdin>", line 1
pattern = re.compile(ur'(«)', re.U)
^
SyntaxError: invalid syntax
由於這是一個語法錯誤,即使在聲明模式之前檢查版本在 Python3 中也不起作用:
>>> import sys
>>> _pattern = r'(«)' if sys.version_info[0] == 3 else ur'(«)'
File "<stdin>", line 1
_pattern = r'(«)' if sys.version_info[0] == 3 else ur'(«)'
^
SyntaxError: invalid syntax
如何對正則表達式進行 unicode 以同時支持 Python2 和 Python3?
盡管在這種情況下,通過刪除文字字符串, r' '
可以很容易地被u' '
替換。
為了理智起見,有一些復雜的正則表達式需要r' '
,例如
re.sub(re.compile(r'([^\.])(\.)([\]\)}>"\'»]*)\s*$', re.U), r'\1 \2\3 ', s)
所以解決方案應該包括文字字符串r' '
用法,除非有其他方法可以繞過它。 但請注意,使用字符串文字或unicode_literals
或來自__future__
是不受歡迎的,因為它會導致大量其他問題,尤其是。 在我使用的代碼庫的其他部分,請參閱http://python-future.org/unicode_literals.html
由於代碼庫不鼓勵 unicode_literals 導入但使用r' '
符號的特定原因是因為填充它並對它們中的每一個進行更改將是非常痛苦的,例如
你真的需要原始字符串嗎? 對於您的示例,需要 unicode 字符串,但不需要原始字符串。 原始字符串很方便,但不是必需的 - 只需將您在原始字符串中使用的任何\
加倍並使用純 unicode。
Python 2 允許將原始字符串與 unicode 字符串連接(產生 unicode 字符串),因此您可以使用r'([^\.])(\.)([\]\)}>"\'' u'»' r']*)\s*$'
在 Python 3 中,它們都是 unicode,所以也可以。
if sys.version_info.major == 2:
pattern = eval("re.compile(ur'(\u00ab)', re.U)")
else:
pattern = re.compile(r'(«)', re.U)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.