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中如果分组了,则会返回和分组数量对应的值,这样,大体也就明白为何返回这么多值了。

猜你喜欢

转载自blog.csdn.net/Bentley_li/article/details/83579298