local start_string = "3, 2, 1, go!"
-- gsub 返回新字符串,所以调用可以链式书写
start_string = start_string
:gsub("1", "one")
:gsub("2", "two")
:gsub("3", "three")
-- start_string = three, two, one, go!
-- 替换所有出现的位置并计数
local one_string = "1 1 1"
local all_replaced, count =
one_string:gsub("1", "one")
-- all_replaced = one one one
-- count = 3
-- 第 4 个参数限制次数
local first_only = one_string:gsub("1", "one", 1)
-- first_only = one 1 1
-- gsub 没有纯文本模式:
-- 第 1 个参数是模式,其中的 "." 匹配任意字符
local price = "1.5"
local as_pattern = price:gsub(".", ",")
-- as_pattern = ,,,
-- 写成 %. 时,点号就只是点号
local as_text = price:gsub("%.", ",")
-- as_text = 1,5
-- 替换串中 % 也是特殊字符:要写成 %%
local percents = one_string:gsub("1", "100%%")
-- percents = 100% 100% 100%
print("start_string = " .. start_string)
print("all_replaced = " .. all_replaced)
print("count = " .. count)
print("first_only = " .. first_only)
print("as_pattern = " .. as_pattern)
print("as_text = " .. as_text)
print("percents = " .. percents)