re.sub("([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )",replace(r'\1')+r'\2'+r'\3',s)
Run Code Online (Sandbox Code Playgroud)
这不会传递第一个组来替换函数,而是r'\1'作为字符串传递.
请说明出了什么问题.
您正在将字符串传递给方法replace.
该组仅在该sub方法中进行评估.您可以单独执行search以获得结果,但未经测试,因为您尚未发布值s或replace函数:
pattern = "([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )"
re.sub(pattern, replace(re.search(pattern, s).group(1))+r'\2'+r'\3',s)
Run Code Online (Sandbox Code Playgroud)
这是另一种可能更适合您的方法:
# this method is called for every match
def replace(match):
group1 = match.group(1)
group2 = match.group(2)
group3 = match.group(3)
# process groups
return "<your replacement>"
s = "<your string>"
pattern = "([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )"
newtext= re.sub(pattern, replace, s)
print(newtext)
Run Code Online (Sandbox Code Playgroud)