Lua中string.find与string.match功能有何差异?
- 内容介绍
- 文章标签
- 相关推荐
本文共计641个文字,预计阅读时间需要3分钟。
我尝试了理解Lua中的`string.find`和`string.match`之间的区别。对我来说,似乎它们都在字符串中找到了一个模式。但有什么区别呢?我应该怎么使用它们呢?比如,如果我有字符串Disk Space: 3000 kB,我想从中提取3000。
`string.find`用于查找子字符串的位置,返回第一个匹配的位置索引,如果没有找到匹配项,则返回-1。它不提取匹配的子字符串。
`string.match`用于查找子字符串并提取它,返回匹配的子字符串,如果没有找到匹配项,则返回nil。
使用示例:
luastr=Disk Space: 3000 kBpattern=:%s*(%d+)%s*
-- 使用string.findindex=string.find(str, pattern)if index then extracted=str:sub(index + 1)else extracted=nilend
-- 使用string.matchmatch=string.match(str, pattern)if match then extracted=matchelse extracted=nilend
在这段代码中,`extracted`将包含3000。
我试图了解Lua中string.find和string.match之间的区别.对我而言,似乎都在字符串中找到了一个模式.但有什么区别?我该如何使用?比方说,如果我有字符串“Disk Space:3000 kB”,我想从中提取’3000′.编辑:好的,我觉得我过于复杂,现在我迷路了.基本上,我需要翻译这个,从Perl到Lua:
my $mem; my $memfree; open(FILE, 'proc/meminfo'); while (<FILE>) { if (m/MemTotal/) { $mem = $_; $mem =~ s/.*:(.*)/$1/; } elseif (m/MemFree/) { $memfree = $_; $memfree =~ s/.*:(.*)/$1/; } } close(FILE);
到目前为止我写的这个:
for Line in io.lines("/proc/meminfo") do if Line:find("MemTotal") then Mem = Line Mem = string.gsub(Mem, ".*", ".*", 1) end end
但这显然是错误的.我得不到什么?我理解为什么它是错的,它实际上在做什么以及为什么我这样做
print(Mem)
它返回
.*
但我不明白什么是正确的方法.正则表达式让我困惑!
local space = tonumber(("Disk Space 3000 kB"):match("Disk Space ([%.,%d]+) kB"))
string.find略有不同,因为在返回任何捕获之前,它返回找到的子字符串的开始和结束索引.当没有捕获时,string.match将返回匹配的整个字符串,而string.find将不会返回超过第二个返回值的任何内容. string.find还允许您使用’plain’参数搜索字符串,而不会知道Lua模式.
当你想要匹配的捕获时使用string.match,当你想要子串的位置时,或者当你想要位置和捕获时,使用string.find.
本文共计641个文字,预计阅读时间需要3分钟。
我尝试了理解Lua中的`string.find`和`string.match`之间的区别。对我来说,似乎它们都在字符串中找到了一个模式。但有什么区别呢?我应该怎么使用它们呢?比如,如果我有字符串Disk Space: 3000 kB,我想从中提取3000。
`string.find`用于查找子字符串的位置,返回第一个匹配的位置索引,如果没有找到匹配项,则返回-1。它不提取匹配的子字符串。
`string.match`用于查找子字符串并提取它,返回匹配的子字符串,如果没有找到匹配项,则返回nil。
使用示例:
luastr=Disk Space: 3000 kBpattern=:%s*(%d+)%s*
-- 使用string.findindex=string.find(str, pattern)if index then extracted=str:sub(index + 1)else extracted=nilend
-- 使用string.matchmatch=string.match(str, pattern)if match then extracted=matchelse extracted=nilend
在这段代码中,`extracted`将包含3000。
我试图了解Lua中string.find和string.match之间的区别.对我而言,似乎都在字符串中找到了一个模式.但有什么区别?我该如何使用?比方说,如果我有字符串“Disk Space:3000 kB”,我想从中提取’3000′.编辑:好的,我觉得我过于复杂,现在我迷路了.基本上,我需要翻译这个,从Perl到Lua:
my $mem; my $memfree; open(FILE, 'proc/meminfo'); while (<FILE>) { if (m/MemTotal/) { $mem = $_; $mem =~ s/.*:(.*)/$1/; } elseif (m/MemFree/) { $memfree = $_; $memfree =~ s/.*:(.*)/$1/; } } close(FILE);
到目前为止我写的这个:
for Line in io.lines("/proc/meminfo") do if Line:find("MemTotal") then Mem = Line Mem = string.gsub(Mem, ".*", ".*", 1) end end
但这显然是错误的.我得不到什么?我理解为什么它是错的,它实际上在做什么以及为什么我这样做
print(Mem)
它返回
.*
但我不明白什么是正确的方法.正则表达式让我困惑!
local space = tonumber(("Disk Space 3000 kB"):match("Disk Space ([%.,%d]+) kB"))
string.find略有不同,因为在返回任何捕获之前,它返回找到的子字符串的开始和结束索引.当没有捕获时,string.match将返回匹配的整个字符串,而string.find将不会返回超过第二个返回值的任何内容. string.find还允许您使用’plain’参数搜索字符串,而不会知道Lua模式.
当你想要匹配的捕获时使用string.match,当你想要子串的位置时,或者当你想要位置和捕获时,使用string.find.

