1

I want to delete two different characters at the beginning and end of my_string with gsub.. But I managed to delete only one..

    local my_string  = "[I wish you a happy birthday]"
    local new_string = bouquet:gsub('%]', '')
    print(new_string)

How can I create the right gsub pattern?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
SweetNGX
  • 153
  • 1
  • 9

4 Answers4

2

you can do something like this:

local new_string = my_string:match("^%[(.*)]$")

explanation: Match a string that starts with [ and ends with ] and return just what's between the two. For any other strings, it will just return them as is.

DarkWiiPlayer
  • 6,871
  • 3
  • 23
  • 38
1

You can use

local new_string = my_string:gsub('^%[(.*)]$', '%1')

See this Lua demo. The ^%[(.*)]$ pattern matches

  • ^ - start of string
  • %[ - a literal [ char
  • (.*) - captures any zero or more chars into Group 1 (%1 refers to this value from the replacement pattern)
  • ] - a ] char
  • $ - end of string.

Alternatively, you can use

local new_string = string.gsub(my_string:gsub('^%[', ''), ']$', '')

See this Lua demo online.

The ^%[ pattern matches a [ at the start of the string and ]$ matches the ] char at the end of the string.

If there is no need to check if [ and ] positions, just use

local new_string = my_string:gsub('[][]', '')

See the Lua demo.

The [][] pattern matches either a ] char or a [ char.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Since you know the basic pattern for gsub, I suggest a easy way to solve you problem.

local new_string = my_string:gsub('%]',''):gsub('%[','')
Renshaw
  • 1,075
  • 6
  • 12
0

So...

do
local my_string="[I wish you a happy birthday]"
local new_string=my_string:gsub('[%[%]]','',2)
print(new_string)
end

...leads to the desired output. The % escapes the [ and ] - Like in other languages the \ do.

koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15