通过尝试在Python2 re编译模式中添加一个fullmatch方法,我基本上是在尝试py2/3兼容性。
我见过关于如何向现有实例添加属性的https://stackoverflow.com/a/2982/2694385。我正在创建https://stackoverflow.com/a/30212799/2694385中给出的方法。
示例代码
import re
import six
regex = re.compile('some pattern') # Better if we keep this same
if six.PY2:
def fullmatch(self_regex, string, flags=0):
return self_regex.match(string, flags=flags)
regex = re.compile(r'(?:' + regex.pattern + r')\Z', flags=regex.flags)
import types
bound = types.MethodType(fullmatch, regex)
# AttributeError here. None of the following three lines work
regex.fullmatch = bound
regex.__setattr__('fullmatch', bound)
setattr(regex, 'fullmatch', bound)发布于 2017-06-27 15:30:50
这是行不通的--正则表达式对象是在C端创建的,它们不代表你的常规实例,所以你不能在Python中修改它们的签名。例如,如果您尝试扩展_sre.SRE_Pattern
import _sre
class CustomPattern(_sre.SRE_Pattern): pass您将得到一个AttributeError,报告_sre模块中不存在这样的对象。如果你试图用以下方式欺骗它:
import re
tmp_pattern = re.compile("")
sre_pat = type(tmp_pattern)
class CustomPattern(sre_pat): pass它会给你一个TypeError,抱怨_sre.SRE_Pattern (它现在是临时存在的,因为它是临时创建的)不是一个可接受的基类型。
相反,您可以在re模块周围创建一个完整的包装器(或者至少向其添加缺少的结构),并在Python端处理Python端的版本差异,尽管我认为这是不值得的。
附注:如果你没有在其他地方使用six,那么没有理由只检查你的Python版本--你可以使用sys.version_info.major < 3。
发布于 2018-09-14 02:19:55
有关您想要的东西,请参阅nlpia.regexes.Pattern --带有fullmatch()方法的_sre.Pattern的科学怪人混搭。这种简单的“继承”方法在Python2和3中有效。
import re
import regex
class Pattern:
""" "Inherits" _sre.SRE_Pattern and adds .fullmatch() method
>>> pattern = Pattern('Aaron[ ]Swartz')
>>> pattern.match('Aaron Swartz')
<_sre.SRE_Match object; span=(0, 12), match='Aaron Swartz'>
>>> pattern.fullmatch('Aaron Swartz!!')
>>> pattern.match('Aaron Swartz!!')
<_sre.SRE_Match object; span=(0, 12), match='Aaron Swartz'>
"""
def __init__(self, pattern):
self._compiled_pattern = re.compile(pattern)
for name in dir(self._compiled_pattern):
if not name in set(('__class__', '__init__', 'fullmatch')):
attr = getattr(self._compiled_pattern, name)
setattr(self, name, attr)
def fullmatch(self, *args, **kwargs):
return regex.fullmatch(self._compiled_pattern.pattern, *args, **kwargs)https://stackoverflow.com/questions/44773522
复制相似问题