Python 2和Python 3之间的re模块更改

Set*_*ton 1 python regex python-2.7 python-3.x

我正在使用在Python 2下开发的代码上运行带有Python 3的单元测试服。所有单元测试都是在Python 2下通过的,但不是在Python 3下通过的。这似乎在的实现上有所变化re,这确实是个难题。为了我。以下是复制我的问题的最小工作示例:

Python 2.7.6 (default, Dec 10 2013, 20:01:46) 
>>> import re
>>> a = re.compile('test', re.IGNORECASE)
>>> assert a.flags == re.IGNORECASE
>>> # No output,  i.e. assertion passed
>>> a.flags
2
>>> re.IGNORECASE
2
Run Code Online (Sandbox Code Playgroud)
Python 3.3.3 (default, Dec 10 2013, 20:13:18)
>>> import re
>>> a = re.compile('test', re.IGNORECASE)
>>> assert a.flags == re.IGNORECASE
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> a.flags
34
>>> re.IGNORECASE
2
Run Code Online (Sandbox Code Playgroud)

显然正在发生一些意料之外的事情!我假设有一些默认标志集flags在python3 中经过或运算后变成34。我想知道的是这些内容,以便通过与适当的标志进行比较来使我的断言通过。作为奖励,这样做的目的是什么?

the*_*eye 5

以下是Python 3.x中的RegEx标志。

import re
print (re.IGNORECASE)
print (re.LOCALE)
print (re.MULTILINE)
print (re.DOTALL)
print (re.UNICODE)
print (re.VERBOSE)
print (re.DEBUG)
print (re.A)
Run Code Online (Sandbox Code Playgroud)

输出量

2
4
8
16
32
64
128
256
Run Code Online (Sandbox Code Playgroud)

docs

字符串是Unicode代码点的不可变序列。

因此,re.UNICODE默认情况下启用标志。既然您已启用re.IGNORECASE,那就可以与它进行“或”运算,re.UNICODE并且可以得到34