二、模式匹配
1. 查找
s = "Hello World Hello";
i, j = string.find(s,"Hello");
print(i,j, string.sub(s,i,j));
i, j = string.find(s,"Hello",2); -- 第三个参数表示从哪里开始搜索
print(i,j, string.sub(s,i,j));
2. string.match 可用于模糊匹配
date = "Today is 17/7/1990";
d = string.match(date,"%d+/%d+/%d+"); -- 返回查到结果
print(d);
3. 替换
s = "Lua is cute very cute";
print(string.gsub(s,"cute","great")); --返回替换后的字符串和替换的次数
print(string.gsub(s,"cute","great",1)); -- 第四个参数限制替换的次数
4. select() 在多个返回值中,获取指定的值
s = "Hi I am Lua ha ha";
count = select(2, string.gsub(s," "," ")); -- 用select获取第二个值
print(count); -- 获取空格的数目
5. string.gmatch函数, 会返回一个函数,通过遍历这个函数,可以获取所有匹配到的元素
words = {};
for w in string.gmatch(s, "%a+") do -- "%a+" 匹配一个或多个字母字符序列
print(w);
words[#words+1]=w;
end;