[英]using re.sub with groups
re.sub("([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )",replace(r'\1')+r'\2'+r'\3',s)
This doesn't pass the first group to replace function and rather passes r'\\1'
as a string. 这不会传递第一个替换函数的组,而是传递
r'\\1'
作为字符串。
Please suggest what is going wrong. 请提出问题所在。
You are passing a string to the method replace. 您正在将字符串传递给方法replace。
The group will only be evaluated in the sub
method. 仅在
sub
方法中评估该组。 You could do a separate search
to get your result, untested though since you have not posted the value from s
nor the replace
function: 您可以进行单独的
search
以得到结果,但未经测试,因为您尚未发布s
或replace
函数的值:
pattern = "([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )"
re.sub(pattern, replace(re.search(pattern, s).group(1))+r'\2'+r'\3',s)
Here is another method possible better suited for you: 这是另一种可能更适合您的方法:
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.