这似乎是一个简单的问题,但显然我缺少一些东西。
我有一个 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/