gpt4 book ai didi

Python RegEx 匹配多行子串,但不会替换它

转载 作者:行者123 更新时间:2023-11-28 22:59:02 25 4
gpt4 key购买 nike

这似乎是一个简单的问题,但显然我遗漏了一些东西。

我有一个 Python 函数,旨在用 HTML 格式的代码替换自定义标签之间出现的代码块:

def subCode(text):
tags = re.findall('<<<mytag>>>.+?<<</mytag>>>', text, re.S)
for tag in tags:
match = re.search('>>>(.+?)<<<', tag, re.S)
replaced_code = replaceCode(match.group(1))
text = re.sub(tag, replaced_code, text, re.S|re.M)
return text

这将匹配标签之间的代码,如下所示:

this is some 
random text
<<<mytag>>>now this
is some
random code<<</mytag>>>
and this is text again

但它不是用格式化的替换替换代码,返回的字符串与输入的相同。我错过了什么?

最佳答案

我想你想使用 re.sub() 的变体,它将函数作为第二个参数,它更简单:

def subCode(text):
return re.sub('<<<mytag>>>(.+?)<<</mytag>>>', replaceFunc, text, flags=re.S)

def replaceFunc(match):
return replaceCode(match.group(1))

如果 re.sub() 的第二个参数是一个函数,它会将匹配对象作为输入并返回替换字符串。

关于Python RegEx 匹配多行子串,但不会替换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com