正则表达式。python保留一组,替换其他组
这是我的密码:正则表达式。python保留一组,替换其他组,python,regex,Python,Regex,这是我的密码: In [1]: import re In [2]: p = 'zxc(.*?)!(.*?)zxc' In [3]: s = 'zxc wololo ! ololo zxc' In [4]: re.sub(pattern=p, repl=r"", string=s) Out[4]: '' In [5]: re.sub(pattern=p, repl=r"\1", string=s) Out[5]: ' wololo ' 期望 问题:
In [1]: import re
In [2]: p = 'zxc(.*?)!(.*?)zxc'
In [3]: s = 'zxc wololo ! ololo zxc'
In [4]: re.sub(pattern=p, repl=r"", string=s)
Out[4]: ''
In [5]: re.sub(pattern=p, repl=r"\1", string=s)
Out[5]: ' wololo '
期望
问题:
如何达到预期的产出
我需要保持第一组的前缀和后缀的模式。假设有两个以上的组
我应该在repl中使用哪个关键字来实现预期结果?您可以使用基于零宽度环视的正则表达式:
>>> s = 'zxc wololo ! ololo zxc'
>>> print re.sub(r'(?<=zxc)([^!]*!).*?(?=zxc)', r'\1', s)
zxc wololo !zxc
在这里:
?您可以使用基于零宽度环视的正则表达式:
>>> s = 'zxc wololo ! ololo zxc'
>>> print re.sub(r'(?<=zxc)([^!]*!).*?(?=zxc)', r'\1', s)
zxc wololo !zxc
在这里:
?repl=rzxc\1!zxc?请参阅并repl=rzxc\1!zxc?看到和