--模式匹配相关函数
--string.find 用于在指定的字符串内搜索指定的模式 返回开始索引的位置和结束索引的位置
--如果无返回nil
--方法带有两个可选参数 第一个是索引指定从改位置搜索 第二个为是否是简单搜索 忽略模式简单字符串匹配
local str = "hello ll"
local i,j = string.find(str,'l')
print(i,j)
local i,j =string.find('a [word]',"[",1,true)
print(i,j)
--string.match
--功能类似string.find 返回值不同 返回值为匹配到的字符串
local s = string.match("Hello World","Hello")
print(s)
local s = string.match("Hello World 4/20/2020","%d+/%d+/%d+")
print(s)
--string.gsub
--三个必选参数 目标字符串 模式 替换字符串
--将目标字符串所有出现模式的地方换成替换字符串
--第四个可选参数 替换次数
--函数第二个返回值 发生替换的次数
local s = string.gsub("Lua is cute","cute","great")
print(s)
--string.gmatch
--返回一个函数 通过返回函数遍历一个字符串中所有可能出现的指定模式
local s = "some string"
local words = {}
for w in string.gmatch(s,"%a+") do --"%a+" 匹配单词
words[#words+1] = w
end
for i=1,#words do
print(words[i])
end
--模式 也是
Lua程序设计-模式匹配
最新推荐文章于 2024-07-10 11:23:37 发布