为Python2和Python3编写unicode正则表达式

时间:2017-04-12 03:08:04

标签: python regex python-2.7 python-3.x unicode

我可以使用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' '符号是因为填充它并且对它们中的每一个进行更改将是非常痛苦的,例如

1 个答案:

答案 0 :(得分:1)

你真的需要原始字符串吗?对于您的示例,需要一个unicode字符串,但不是原始字符串。原始字符串是一种方便,但不是必需的 - 只需将原始字符串中使用的任何\加倍并使用普通的unicode。

Python 2允许将原始字符串与unicode字符串连接(产生unicode字符串),因此您可以使用r'([^\.])(\.)([\]\)}>"\'' u'»' r']*)\s*$'
在Python 3中,它们都将是unicode,因此也可以使用。

相关问题