Reputation: 163
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?
Upvotes: 1
Views: 556
Reputation: 2793
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.
Upvotes: 0
Reputation: 1155
Since you know the basic pattern for gsub, I suggest a easy way to solve you problem.
local new_string = my_string:gsub('%]',''):gsub('%[','')
Upvotes: 0
Reputation: 626926
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.
Upvotes: 1
Reputation: 7066
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.
Upvotes: 2