Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 正则表达式子方法不会替换python正则表达式中的所有引用_Regex_Python 3.x - Fatal编程技术网

Regex 正则表达式子方法不会替换python正则表达式中的所有引用

Regex 正则表达式子方法不会替换python正则表达式中的所有引用,regex,python-3.x,Regex,Python 3.x,我试图使用正则表达式子方法,但它并不能替换所有出现的情况。请参阅下面的代码。我想用“and”替换所有出现的“&&”。表达式中有一个前导空格和尾随空格 >>> string =" && && 7978888 && 896" >>> tmp = re.sub("( && )"," and ",string) >>> tmp ' and && 7978888 and 8

我试图使用正则表达式子方法,但它并不能替换所有出现的情况。请参阅下面的代码。我想用“and”替换所有出现的“&&”。表达式中有一个前导空格和尾随空格

>>> string =" && && 7978888 && 896"
>>> tmp = re.sub("( && )"," and ",string)
>>> tmp
' and && 7978888 and 896'

请提供帮助。

您可以在正则表达式中使用lookarounds,因为您有重叠的匹配项:

(?<= )&&(?= )
(?>>string=“&&&&&7978888&&896”

>>>tmp=re.sub(r“(?这里的混淆是两个&&之间只有一个空格。 如果有两个空格,那么它会像预期的那样工作,但是为什么要费心在regex模式中包含空格呢?“(&&&”)会不会工作得不好

>>重新导入
>>>string=“&&&&7978888&&896”
>>>tmp=re.sub(r“&&“,”和“,”字符串)
>>>tmp
'和&&7978888和896'
如果这还不够,您还需要遵循哪些独特的约束

>>> string =" && && 7978888 && 896"
>>> tmp = re.sub(r"(?<= )&&(?= )", "and", string)
>>> tmp
' and and 7978888 and 896'