相关疑难解决方法(0)

在python 3.7中检索python 3.6处理re.sub()与零长度匹配

使用python 3.7改变零长度匹配的处理.请考虑以下python 3.6(和之前的版本):

>>> import re
>>> print(re.sub('a*', 'x', 'bac'))
xbxcx
>>> print(re.sub('.*', 'x', 'bac'))
x
Run Code Online (Sandbox Code Playgroud)

我们使用python 3.7得到以下内容:

>>> import re
>>> print(re.sub('a*', 'x', 'bac'))
xbxxcx
>>> print(re.sub('.*', 'x', 'bac'))
xx
Run Code Online (Sandbox Code Playgroud)

我知道这是PCRE的标准行为.此外,re.finditer()似乎总是检测到额外的匹配:

>>> for m in re.finditer('a*', 'bac'):
...     print(m.start(0), m.end(0), m.group(0))
...
0 0
1 2 a
2 2
3 3
Run Code Online (Sandbox Code Playgroud)

也就是说,我有兴趣检索python 3.6的行为(这是一个在python中实现sed的业余爱好项目).

我可以提供以下解决方案:

def sub36(regex, replacement, string):

    compiled = re.compile(regex)

    class Match(object):
        def __init__(self):
            self.prevmatch = None
        def __call__(self, match):
            try:
                if match.group(0) == …
Run Code Online (Sandbox Code Playgroud)

python regex python-3.x python-3.6 python-3.7

6
推荐指数
1
解决办法
203
查看次数

标签 统计

python ×1

python-3.6 ×1

python-3.7 ×1

python-3.x ×1

regex ×1