Lua字符串模式 - 更短的代码

有没有可能只使用一个 gsub 就可以得到相同的结果,而不是两个?

a=[[do end workspace.Part["Child 1"].Object.child2["thing"]remove() do end]]
a=a:gsub("(%[%s*[\'\"]?%w+[\'\"]?%s*%]%[?[\'\"]?%w+[\'\"]?%]?):?%s*remove%(%)","filterremove(%1)")
输出: do end filterremove(Workspace.Part["Child 1"].Object.child2["thing"]) do end

无论 x.y、 x\ [y]、\ [x] \ [y] 等组合是如何,都能够转换。

点赞
用户1442917
用户1442917
`a:gsub("(%S*%b[]):remove%(%)", "filterremove(%1)")`

a 字符串中匹配到的所有形如 加上一系列非空白字符以及 的内容,并紧随其后的 .remove() 替换为 filterremove(匹配到的内容) ,并返回替换后的字符串。

2013-02-28 16:15:01
用户102441
用户102441

你至少可以链式组合和换行:

a = [[do end workspace.Part["Child 1"]:remove() do end]]
a = a:gsub("%.%a+","{F}%0{F}")
     :gsub('(%[%s*([\'"]?).*%2%s*%]):remove%(%)','{F}%1{F}:remove()')
     :gsub('{F}%s*{F}','')
     :gsub('{F}.-{F}','filterremove(%0)')

不过,实际上,这永远不会奏效。比如:

workspace.remove(x)
workspace["remove"](x)
getfenv()["work" .. "space"]["re".."move"](x)
2013-02-28 16:29:22