San*_*jay 2 regex lua lua-patterns
我想替换花括号,它的意思是something in here {uid} {uid2}to something in here :id :id。
我尝试了以下方法:
local v = "something in here {uid} {uid2}"
local regex = "^{([^}]+)}"
print(v:gsub(v:match(regex), ":id"):gsub("{", ""):gsub("}", ""))
Run Code Online (Sandbox Code Playgroud)
但这是行不通的。但是,当我删除“这里的东西”时,它确实起作用。请帮忙。
要替换大括号内的所有子字符串,其中不包含任何其他大括号
v:gsub("{[^{}]*}", ":id")
Run Code Online (Sandbox Code Playgroud)
参见Lua演示:
local v = "something in here {uid} {uid2}"
res, _ = v:gsub("{([^{}]*)}", ":id")
print(res)
-- something in here :id :id
Run Code Online (Sandbox Code Playgroud)
的{[^{}]*}图案相匹配的{,则比其他任何0以上字符{和},然后}。
替代解决方案
{.-}将匹配{,然后将任何0+个字符减为最少(-是一个惰性量词),然后是一个}char(请参见此演示)v:gsub("%b{}", ":id")(请参见demo),%b{}则将匹配嵌套花括号内的子字符串。