gpt4 book ai didi

Python 正则表达式 - 替换除大括号之间的所有字符

转载 作者:行者123 更新时间:2023-11-28 19:58:33 28 4
gpt4 key购买 nike

我有点受困于正则表达式。我有一个格式为

的字符串
{% 'ello %} wor'ld {% te'st %}

我只想转义不在 {% ... %} 标签之间的撇号,所以预期的输出是

{% 'ello %} wor"ld {% te'st %}

我知道我可以只使用字符串 replace 函数替换所有这些,但是我不知道如何使用正则表达式来匹配那些外面的括号

最佳答案

这可能可以用正则表达式来完成,但它会很复杂。如果您直接这样做,则更容易编写和阅读:

def escape(s):
isIn = False
ret = []
for i in range(len(s)):
if not isIn and s[i]=="'": ret += ["""]
else: ret += s[i:i+1]

if isIn and s[i:i+2]=="%}": isIn = False
if not isIn and s[i:i+2]=="{%": isIn = True

return "".join(ret)

关于Python 正则表达式 - 替换除大括号之间的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8030764/

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