我试图使用正则表达式子方法,但不能替换所有出现的子方法。请参见下面的代码。我想将所有出现的“ &&”替换为“和”。表达式中有一个前导空间和尾随空间。
>>> string =" && && 7978888 && 896"
>>> tmp = re.sub("( && )"," and ",string)
>>> tmp
' and && 7978888 and 896'
请帮忙。
由于匹配项重叠,因此可以在正则表达式中使用环视:
(?<= )&&(?= )
码:
>>> string =" && && 7978888 && 896"
>>> tmp = re.sub(r"(?<= )&&(?= )", "and", string)
>>> tmp
' and and 7978888 and 896'
在这里使用lookbehind和lookahead断言使regex引擎仅断言前后是否存在空间,而&&
没有实际移动当前位置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句