Lua模式匹配问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_33442459/article/details/75007307

string.gsub(s,pattern,reps,n)

将s中所有符合pattern的字串替换为reps,返回结果串+匹配数
第1个参数:源字符串
第2个参数:待替换之模式串
第3个参数:替换为reps。
可以是string,
也可以是函数,用捕获的内容作为参数调用该函数,将返回的内容作为替换字符串,
也可以是table,用捕获的内容为key去取table的值来作为替换字符串,如果不存在,就不做替换。
第四个参数:可选,当它被指定时, string.gsub()函数只对源字符串中的前n个成功配对的成员进行操作.

print(string.gsub("hello,world","o","a"))  -->hella,warld   2
print(string.gsub("Lua is cute","cute","great"))  -->Lua is great
print(string.gsub("all lii","l","x",2))    -->axx lii
_,count=string.gsub(str," "," ")           --计算一个字符串中空格出现的次数(第二个返回值表示替换的次数)
下面的表列出了Lua支持的所有字符类:
--上面字符类的大写形式表示小写所代表的集合的补集,例如,'%A'非字母的字符
print(string.gsub("hello, up-down!","%A","."))           -->hello..up.down. 4
--数字4不是字符串结果的一部分,他是gsub返回的第二个结果,代表发生替换的次数
print(string.gsub("hello Lua","(%w+)%s*(%w+)","%2 %1"))  -->Lua hello 1
string.gsub("hello world","l+",functions(s) return "xxx" end)
print(s,n)   -->hexxxo worxxxd 2
string.gsub("hello world","%w+",print) -->hello world 2
lookupTable={["hello"]="hola",["world"]="mundo"}
print(string.gsub("hello world","(%w+)",lookupTable)) -->hola mundo 2


猜你喜欢

转载自blog.csdn.net/sinat_33442459/article/details/75007307
今日推荐