【问题标题】:Lua regex to replace curly bracesLua 正则表达式替换花括号
【发布时间】:2020-01-07 07:08:43
【问题描述】:

我想替换花括号和里面的单词,即something in here {uid} {uid2}something in here :id :id

我尝试了以下方法:

local v = "something in here {uid} {uid2}"
local regex = "^{([^}]+)}"

print(v:gsub(v:match(regex), ":id"):gsub("{", ""):gsub("}", ""))

但它不起作用。但是,当我删除“这里的东西”时它确实有效。请帮忙。

【问题讨论】:

  • ^ 表示字符串开始。如果您不想将匹配限制为仅出现在开头,请将其删除。
  • @WiktorStribiżew 这不是全球性的吗?我的意思是对于 url /api/{parentId}/{childId},我得到了`/api/data/lookups/something/childId`。那个 childId 没有被替换。
  • 不,^ 并不意味着全局。另外,我认为您只需要v:gsub("{[^{}]*}", ":id"),请参阅demo
  • 非常感谢@WiktorStribiżew。你能告诉我如何用花括号替换所有单词吗?我是lua模式的新手,所以我还在学习。如果您指导/告诉我,这将是一个很大的帮助。
  • @WiktorStribiżew 哦抱歉没有看到演示

标签: regex lua lua-patterns


【解决方案1】:

要替换花括号内不包含任何其他花括号的所有子字符串,您可以使用

v:gsub("{[^{}]*}", ":id")

Lua demo

local v = "something in here {uid} {uid2}"
res, _ = v:gsub("{([^{}]*)}", ":id")
print(res)
-- something in here :id :id

{[^{}]*} 模式匹配{,然后是除{} 之外的任何0 个或多个字符,然后是}

替代解决方案

  • {.-} 将匹配 {,然后是尽可能少的任何 0+ 字符(- 是一个惰性量词),然后是 } 字符(参见 this demo
  • 如果嵌套花括号数量均衡,您可以使用v:gsub("%b{}", ":id")(请参阅demo),%b{} 将匹配嵌套花括号内的子字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多