匹配符 |
作用 |
示例 |
%a |
任意字母(A-Z, a-z) |
"%a+" 匹配连续字母 |
%d |
任意数字(0-9) |
"%d%d" 匹配两个数字 |
%s |
空白字符(空格、制表符等) |
"%s+" 匹配连续空白 |
%w |
字母或数字(等同于 [%a%d] ) |
"%w+" 匹配单词 |
%l |
小写字母 |
"%l+" 匹配小写字符串 |
%u |
大写字母 |
"%u+" 匹配大写字符串 |
%x |
十六进制数字(0-9, A-F, a-f) |
"%x+" 匹配十六进制数 |
%p |
标点符号 |
"%p+" 匹配标点 |
%c |
控制字符(如换行符 \n ) |
"%c" 匹配控制字符 |
. |
任意字符(除换行符) |
".+" 匹配任意内容 |
类型 |
匹配符 |
示例 |
---------- |
-------------------------- |
----------------------------- |
字符类 |
%a , %d , %s |
"%a%a%a" 匹配三个字母 |
量词 |
+ , * , - , ? |
"%d-%.%d+" 匹配小数 |
锚点 |
^ , $ |
^%d+ 匹配开头的数字 |
转义 |
%% , %. |
"escape%%" 匹配 "escape%" |
自定义集合 |
[0-9A-F] |
"[aeiou]" 匹配元音 |
捕获组 |
() |
"(%d+)-(%d+)" 提取日期 |
-- --string.match -- 匹配字符串中第一个符合条件的字符
-- local s = "hello world from Lua"
-- local aa = string.match(s,"%a+",5)
-- print(aa)
--string.gmatch匹配字符串 返回一个迭代器函数
-- local text = "姓名=张三,年龄=11,财富=100块"
local text = "fullName=张三,age=11岁,wealth=100块"
local words = {}
-- 提取所有连续中文字符 按"="分割
for word in string.gmatch(text, "=([^,]+)") do--用+号来输出完整字节(因为中文是每个字2个字节)
table.insert(words, word)--取到的值插入table
end
print(table.concat(words, "|"))
-- local text = "姓名=张三,年龄=11,财富=100块"
local text = "fullName=张三,age=11岁,wealth=100块"
local words = {}
-- 提取所有连续中文字符
for word in string.gmatch(text, "([^,]+)=([^,]+)") do--用+号来输出完整字节(因为中文是每个字2个字节)
table.insert(words, word)--取到的值插入table
end
for k , v in string.gmatch(text, "([^,]+)=([^,]+)") do
print(k , v)--迭代取出主键跟键值并打印
end
-- local text = "姓名=张三,年龄=11,财富=100块"
local text = "fullName=张三|age=11岁|wealth=100块"
local words = {}
-- 提取所有连续中文字符
for word in string.gmatch(text, "([^|]+)=([^|]+)") do--用+号来输出完整字节(因为中文是每个字2个字节)
table.insert(words, word)--取到的值插入table
end
for k , v in string.gmatch(text, "([^|]+)=([^|]+)") do
print(k , v)--迭代取出主键跟键值并打印
end
--string.gsub (s, pattern, repl [, n]) --替换函数将pattern(匹配的模式)替换成repl(替换的内容) [, n]是替换次数这个是可选参数
local str = "hello word Lua18 hello"
local aa = string.gsub(str,"hello","你好",1)
local bb = str:gsub("hello","我很好",1)
print(aa)
print(bb)
--string.sub (s, i [, j]) -- 提取内容的位置i-j
local s = "hello word lua 你好吗" --设定一个字符串s
local aa = s:sub(-6) -- 提取字符串s的后6个字节
local bb = s:sub(1,5) -- 提取字符串s的第一个到第五个字节
print(aa.."--"..bb) -- 打印输出:你好吗--hello
local s = "ly/a26.png" --设定一个图片路径作为字符串s
print(s:find("%.")) --打印字符串中"."的位置,输出内容:7 7
print(s:sub(1,s:find("%.")-1)) -- 提取字符串中第一个到"."前一个位置的字节,打印输出内容:ly/a26