使用re.sub和分组

1 投票
1 回答
644 浏览
提问于 2025-04-18 08:50
re.sub("([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )",replace(r'\1')+r'\2'+r'\3',s) 

这段话的意思是,代码没有把第一个分组的内容传递给替换函数,而是把 r'\1' 当作一个字符串传了进去。

请帮忙看看哪里出错了。

1 个回答

5

你正在把一个字符串传递给替换的方法。

这个组只会在sub方法中被评估。你可以单独使用search来获取结果,不过这部分没有经过测试,因为你没有提供s的值和replace函数:

pattern = "([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )"
re.sub(pattern, replace(re.search(pattern, s).group(1))+r'\2'+r'\3',s)

这里还有另一种方法,可能更适合你:

# 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)

撰写回答