
字符匹配.jpg
前言#
今天我們?cè)僖黄鹂匆粋€(gè)string家族的匹配函數(shù),它不同于函數(shù)string.find()要返回匹配字符的索引,也不同于string.gmatch()函數(shù)會(huì)返回一個(gè)迭代函數(shù)可以取到所有的匹配項(xiàng),這個(gè)函數(shù)它僅僅范回第一個(gè)匹配,簡(jiǎn)單易用,往往在一些實(shí)際應(yīng)用中找到第一個(gè)匹配就夠了,我們一起來(lái)看一下用法。
string.match()##
- 原型:string.match(s, pattern [, init])
- 解釋:在字符串
s中查找滿足參數(shù)pattern的匹配子串,如果找到了一個(gè)匹配就返回這個(gè)匹配子串,若沒(méi)找到則返回nil,如果參數(shù)pattern沒(méi)有指定匹配參數(shù),則返回整個(gè)匹配字符串——"If pattern specifies no captures, then the whole match is returned."(這一句我翻譯的不太靠譜啊,有問(wèn)題麻煩大家給我指正一下),另外,一個(gè)數(shù)字形參數(shù)init用來(lái)指定查找字符串的其實(shí)位置,這個(gè)參數(shù)默認(rèn)為1,當(dāng)然也可以設(shè)置為負(fù)數(shù),即-n表示從字符串尾部向前數(shù)n個(gè)字符開(kāi)始查找。
Usage##
- 首先新建一個(gè)文件將文件命名為matchtest.lua然后編寫(xiě)如下代碼:
local sourcestr = "ehre99wj=--=-*-/4mdqwl\0ds123fef"
print("\nsourcestr = "..sourcestr)
local match_ret = string.match(sourcestr, "%d%d%d")
print("\nmatch_ret is "..match_ret)
match_ret = string.match(sourcestr, "%d%a%a")
print("\nmatch_ret is "..match_ret)
match_ret = string.match(sourcestr, "")
print("\nmatch_ret is "..match_ret)
match_ret = string.match(sourcestr, "%d%d")
print("\nmatch_ret is "..match_ret)
match_ret = string.match(sourcestr, "%d%d", 10)
print("\nmatch_ret is "..match_ret)
- 運(yùn)行結(jié)果

string_match.png
總結(jié)#
- 由第一組結(jié)果可以看出
string.match()在遇到\0時(shí)不會(huì)停止查找,而是一直查找到字符串結(jié)尾。 - 最后兩組結(jié)果對(duì)比可以發(fā)現(xiàn)參數(shù)
init的作用,他指定了搜索匹配的起始位置。 - 這一篇中有一個(gè)關(guān)于官方文檔的翻譯的疑惑,就是"If pattern specifies no captures, then the whole match is returned.",我總感覺(jué)我怎么翻譯都不太對(duì),麻煩明白的大神給我講一下是什么意思,其實(shí)給我舉個(gè)例子就明白了。