Axel
Axel

Reputation: 5111

Lua regex to replace curly braces

I want to replace curly braces and it's word inside i.e. something in here {uid} {uid2} to something in here :id :id.

I tried the following:

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

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

But it doesn't work. However, it does work when I remove "something in here ". Please help.

Upvotes: 2

Views: 844

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

To replace all substrings inside curly braces that do not contain any other curly braces inside you may use

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

See the Lua demo:

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

The {[^{}]*} pattern matches a {, then any 0 or more chars other than { and }, and then }.

Alternative solutions

  • {.-} will match {, then any 0+ chars as few as possible (- is a lazy quantifier), and then a } char (see this demo)
  • If you have a balanced amount of nested curly braces you may use v:gsub("%b{}", ":id") (see demo), %b{} will match substrings inside nested curly braces.

Upvotes: 5

Related Questions