Python 如何';动态';将正则表达式编译为(非)二进制?
我开始修改我的python框架,使之与python 3兼容。我遇到了一个问题:正则表达式匹配的类型错误。事实证明,我的一些正则表达式需要编译为二进制,以避免在与其他函数生成的字节进行匹配时出现类型错误 所以我想写一些像这样的东西Python 如何';动态';将正则表达式编译为(非)二进制?,python,regex,Python,Regex,我开始修改我的python框架,使之与python 3兼容。我遇到了一个问题:正则表达式匹配的类型错误。事实证明,我的一些正则表达式需要编译为二进制,以避免在与其他函数生成的字节进行匹配时出现类型错误 所以我想写一些像这样的东西 @classmethod def contains(cls, pattern, value): """ :param pattern: A regular expression pattern. If input is plain string, wil
@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)
确保使用与“其他函数”相同的编码
您可以使用上述方法转换为字节,但我建议您将另一个函数提供的值转换为unicode
确保使用与“其他函数”相同的编码
您可以使用上述方法转换为字节,但我建议您将另一个函数提供的值转换为unicode。这里的关键是
b'{}'
在python2和python3中给出不同的结果:
蟒蛇2.7:
type(b'{}') # <type 'str'>
因此它在2.7中工作,因为格式是str
的一种方法
您需要使用这里的关键是,
b'{}
在python2和python3中给出不同的结果:
蟒蛇2.7:
type(b'{}') # <type 'str'>
因此它在2.7中工作,因为格式是str
的一种方法
您需要使用,只是为了完整性:另一个解决方案是不更改正则表达式的类型,而是更改传入数据的类型,例如:
if value is bytes:
value = str(value)
为了完整性:另一个解决方案是不更改正则表达式的类型,而是更改传入数据的类型,例如:
if value is bytes:
value = str(value)
if value is bytes:
value = str(value)