Skip to main content
 首页 » 编程设计

python之Python 2 和 Python 3 之间 re 模块的变化

2025年05月04日13daizhj

我正在使用 Python 3 对在 Python 2 下开发的代码运行我的单元测试套件。所有单元测试都在 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 

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 

显然发生了一些我没有预料到的事情!我假设在 python3 中有一组默认标志,它们通过 OR 组合在一起使 flags 为 34。我想知道的是这些是什么,以便我可以通过与适当的标志进行比较来使我的断言通过。作为奖励,这样做的目的是什么?

请您参考如下方法:

以下是 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) 

输出

2 
4 
8 
16 
32 
64 
128 
256 

来自docs ,

Strings are immutable sequences of Unicode code points.

因此,re.UNICODE 标志默认启用。由于您启用了 re.IGNORECASE,它与 re.UNICODE 进行或运算,得到 34。