string库的相关应用

发布于 2020-12-18 21:41:26

基本函数

函数描述示例结果
len计算字符串长度string.len("abcd")4
rep返回字符串s的n个拷贝string.rep("abcd",2)abcdabcd
lower返回字符串全部字母大写string.lower("AbcD")abcd
upper返回字符串全部字母小写string.upper("AbcD")ABCD
format格式化字符串string.format("the value is:%d",4)the value is:4
sub从字符串里截取字符串string.sub("abcd",2)bcd
string.sub("abcd",-2)cd
string.sub("abcd",2,-2)bc
string.sub("abcd",2,3)bc
find在字符串中查找(显示位置)string.find("cdcdcdcd","ab")nil
string.find("cdcdcdcd","cd")1 2
string.find("cdcdcdcd","cd",7)7 8
match在字符串中查找(显示内容)string.match("cdcdcdcd","ab")nil
string.match("cdcdcdcd","cd")cd
gsub在字符串中替换string.gsub("abcdabcd","a","z");zbcdzbcd 2
string.gsub("aaaa","a","z",3);zzza 3
byte返回字符的整数形式string.byte("ABCD",4)68
char将整型数字转成字符并连接string.char(97,98,99,100)abcd

基本模式串

字符类描述示例结果
.任意字符string.find("",".")nil
%s空白符string.find("ab cd","%s%s")3 4
%S非空白符string.find("ab cd","%S%S")1 2
%p标点字符string.find("ab,.cd","%p%p")3 4
%P非标点字符string.find("ab,.cd","%P%P")1 2
%c控制字符string.find("abcdtn","%c%c")5 6
%C非控制字符string.find("tnabcd","%C%C")3 4
%d数字string.find("abcd12","%d%d")5 6
%D非数字string.find("12abcd","%D%D")3 4
%x十六进制数字string.find("efgh","%x%x")1 2
%X非十六进制数字string.find("efgh","%X%X")3 4
%a字母string.find("AB12","%a%a")1 2
%A非字母string.find("AB12","%A%A")3 4
%l小写字母string.find("ABab","%l%l")3 4
%L大写字母string.find("ABab","%L%L")1 2
%u大写字母string.find("ABab","%u%u")1 2
%U非大写字母string.find("ABab","%U%U")3 4
%w字母和数字string.find("a1()","%w%w")1 2
%W非字母非数字string.find("a1()","%W%W")3 4

转义字符%

字符类描述示例结果
%转义字符string.find("abc%..","%%")4 4
string.find("abc..d","%.%.")4 5

用[]创建字符集,"-"为连字符,"^"表示字符集的补集

字符类描述示例结果
[01]匹配二进制数string.find("32123","[01]")3 3
AB匹配AC、AD、BC、BDstring.find("ABCDEF","AB")2 3
[[]]匹配一对方括号[]string.find("ABC[]D","[[]]")4 5
[1-3]匹配数字1-3string.find("312","1-3[1-3]")1 3
[b-d]匹配字母b-dstring.find("dbc","b-d[b-d]")1 3
[^%s]匹配任意非空字符string.find(" a ","[^%s]")3 3
[^%d]匹配任意非数字字符string.find("123a","[^%d]")4 4
[^%a]匹配任意非字母字符string.find("abc1","[^%a]")4 4

用"()"进行捕获

字符类描述示例结果
()捕获字符串string.find("12ab","(%a%a)")3 4 ab
string.find("ab12","(%d%d)")3 4 12

模式修饰符

修饰符描述示例结果
+表示1个或多个,匹配最多个string.find("aaabbb","(a+b)")1 4 aaab
string.find("cccbbb","(a+b)")nil
-表示0个或多个,匹配最少个string.find("zzxyyy","(xy-)")3 3 x
string.find("zzzyyy","(x-y)")4 4 y
*表示0个或多个,匹配最多个string.find("mmmnnn","(m*n)")1 4 mmmb
string.find("lllnnn","(m*n)")4 4 n
?表示0个或1个string.find("aaabbb","(a?b)")3 4 ab
string.find("cccbbb","(a?b)")4 4 b

match的常见用法

描述示例结果
匹配中文string.match("男女abc123","([^%w%p]+)")男女
匹配英文string.match("男女abc123","(%a+)")abc
匹配数字string.match("男女abc123","(%d+)")123
匹配英文和数字string.match("男女abc123","(%w+)")abc123
0 条评论

发布
问题