lua使用string.match()時遇到的一些問題記錄

在某個地方看到了一行lua代碼,當時沒看懂爲什麼返回了這麼多值

local strContent = [[abcde  csdn = {博客}  csdn.net]]

local strPattern = [[^(.*)(csdn%s*=%s*)(%b{})(.*)$]]

local strCapture1, strCapture2, strCapture3, strCapture4 = string.match(strContent, strPattern)

他返回的結果爲:

strCapture1:  abcde
strCapture2:  csdn =
strCapture3:  {博客}
strCapture4:    csdn.net

當時完全弄不明白,對着菜鳥教程上的講義看了很多遍 ,講義如下:

string.match(str, pattern, init)
string.match()只尋找源字串str中的第一個配對. 參數init可選, 指定搜尋過程的起點, 默認爲1。 
在成功配對時, 函數將返回配對表達式中的所有捕獲結果; 如果沒有設置捕獲標記, 則返回整個配對字符串. 當沒有成功的配對時, 返回nil

思來想去,偶然發現這裏有四個返回值,而上面正則表達式大致也可以分爲四個部分,這麼一說的話,是不是可以有更多個返回值呢,動手實驗纔是王道:

local strContent = [[I Have a Dream i_have =  {  2018-08-08 08:08:08  }  dream  Martin Luther King  abcde]]

local strPattern = [[^(.*)(i_have%s*=%s*)(%b{})(.*)(Martin)(.*)$]]
local strCapture1, strCapture2, strCapture3, strCapture4, strCapture5, strCapture6 = string.match(strContent, strPattern)

print("strCapture1:  " .. strCapture1)
print("strCapture2:  " .. strCapture2)
print("strCapture3:  " .. strCapture3)
print("strCapture4:  " .. strCapture4)
print("strCapture5:  " .. strCapture5)
print("strCapture6:  " .. strCapture6)

這樣,我把正則表達式分了六個部分,是不是真會給我返回六個值呢,我們來看打印結果:

strCapture1:  I Have a Dream
strCapture2:  i_have =
strCapture3:  {  2018-08-08 08:08:08  }
strCapture4:   dream
strCapture5:  Martin
strCapture6:   Luther King  abcde

果然如此,這就想不明白了,於是網上各種查資料,在一篇文章(文章鏈接:https://www.cnblogs.com/meamin9/p/4502461.html)中找到這麼一句話:

string.match(s, pattern[, init])

在字符串s中匹配pattern,如果匹配失敗返回nil。否則,當pattern中沒有分組時,返回第一個匹配到的子串;當pattern中有分組時,返回第一個匹配到子串的分組,多個分組就返回多個。可選參數init表示匹配字符串的起始索引,缺省爲1,可以爲負索引。

注意標紅的這一段話,pattern中如果分組了,則會返回和分組數量對應的值,這樣,大體也就明白爲何返回這麼多值了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章