Skip to main content
 首页 » 编程设计

python之如何将 'dynamically' 正则表达式编译为(非)二进制

2025年05月04日32bhlsheji

我开始重新设计我的 python 框架,使其与 python3 兼容。我遇到的一个问题:我的正则表达式匹配的类型错误。事实证明,我的 一些 正则表达式需要编译为二进制文件,以避免在与其他函数生成的字节匹配时出现类型错误。

所以我想写这样的东西

@classmethod 
def contains(cls, pattern, value): 
    """ 
    :param pattern: A regular expression pattern. If input is plain string, will be compiled on the fly 
    :param value: A string that might contain the given pattern (can be multi line string) 
    :returns: True if pattern is found in value 
    """ 
    compiled_pattern = pattern 
    if type(pattern) is str: 
        if type(value) is bytes: 
            print("binary pattern") 
            compiled_pattern = re.compile(b'{}'.format(pattern)) 
        else: 
            print("normal pattern") 
            compiled_pattern = re.compile(pattern)         
 
    if compiled_pattern.search(value) is None: 
        return False 
    return True 

创建“正常”模式效果很好,但对于“二进制”模式,我明白了

compiled_pattern = re.compile(b'{}'.format(pattern)) 
AttributeError: 'bytes' object has no attribute 'format' 

(这个错误是针对python3的;python2直接给我抛出语法错误)

那么,我如何指示 python 从变量编译正则表达式,但作为二进制?

(我知道还有其他方法可以解决根本问题;例如通过在那个方法中执行 value = str(value) )

请您参考如下方法:

这里的关键是 b'{}' 在 python2 和 python3 中给你不同的结果:

python 2.7:

type(b'{}') # <type 'str'> 

python 3:

type(b'{}') # <class 'bytes'> 

实际发生了什么,它是这样做的吗:

(b'{}').format(pattern) 

因此它在 2.7 中工作,因为 format 是 str 的一种方法。

您需要使用 bytes(pattern, encoding)