admin 管理员组

文章数量: 1087135


2023年12月23日发(作者:eclipse修改背景颜色)

用法

(pattern)可以用于在一个字符串中查找模式匹配,返回匹配结果。其中参数pattern为正则表达式,可以用来描述所需的匹配模式。函数会返回匹配到的第一个子串的起始和结束位置以及匹配子串本身。

例如:

local str = "Hello, World!"

local pattern = "o"

local start, finish, match = str:match(pattern)

print(start, finish, match)

这段代码会输出3,4,"o",表示在字符串 "Hello, World!" 中匹配到了第一个字母 o,并且它在字符串中的起始位置是 3,终止位置是 4。

如果想匹配到多个子串,可以在pattern中使用捕获组。例如:

local str = "I am 25 years old and she is 30 years old."

local pattern = "(%d+) years old"

for age in str:gmatch(pattern) do

print(age)

end

这段代码会输出25和30,表示在字符串 "I am 25 years old and she is 30

years old." 中匹配到了两个年龄数字,并把它们作为迭代器的值返回。


本文标签: 匹配 返回 字符串 位置 子串