今天在学习lua,熟悉项目代码的过程中,发现string.gsub好高级,所以在此mark下。
以下是lua5.1的官方文档介绍。
string.gsub (s, pattern, repl [, n]) Returns a copy of s in which all occurrences of the pattern have been replaced by a replacement string specified by repl, which may be a string, a table, or a function. gsub also returns, as its second value, the total number of substitutions made.
If repl is a string, then its value is used for replacement. The character % works as an escape character: any sequence in repl of the form %n, with n between and , stands for the value of the n-th captured substring (see below). The sequence % stands for the whole match. The sequence %% stands for a single %. If repl is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key. If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument. If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string). The optional last parameter n limits the maximum number of substitutions to occur. For instance, when n is only the first occurrence of pattern is replaced. Here are some examples: x = string.gsub("hello world", "(%w+)", "%1 %1")
--> x="hello hello world world" x = string.gsub("hello world", "%w+", "%0 %0", )
--> x="hello hello world" x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
--> x="world hello Lua from" x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
--> x="home = /home/roberto, user = roberto" x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
return loadstring(s)()
end)
--> x="4+5 = 9" local t = {name="lua", version="5.1"}
x = string.gsub("$name%-$version.tar.gz", "%$(%w+)", t)
--> x="lua-5.1.tar.gz"
string.gsub (s, pattern, repl [, n])
使用范例:
一、repl为function的情况。
1、将已知格式字符串中的数字提取出来。
test_str_gsub = function(str, pat)
-- 这里只想取出两个值.
local ret1, ret2 = -, -
local func = function(a, b)
-- lua新手, 不知道此处是否还有其他方式可以取出这里的a, b
ret1, ret2 = a, b
end -- 返回值为被操作后的字符串, 和匹配到的数量
local new_str, matched_count = string.gsub(str, pat, func)
print('test_str_gsub result,', new_str, matched_count) return ret1, ret2
end -- 请注意这里pat里面的括号, 代表你想要导出并传递给func的参数
print('got numbers,', test_str_gsub('20-15', '(%d+)-(%d+)'))
1 > test_str_gsub result, -
2 > got numbers,
2、替换掉字符串中匹配到的部分。
-- 将一段格式替换为一个随机数
parse_random_question = function(ques)
local pat = "@R=(%d+)-(%d+)@" -- 当然,这个pat也可传参 local rep_func = function(num1, num2)
return math.random(num1, num2)
end ques = string.gsub(ques, pat, rep_func)
return ques
end print(parse_random_question('中间(@R=1-100@)是一个随机数'))
> 中间()是一个随机数
Continue learning ...
如果大大看见错误地方,还请指正,谢谢。