Lua中string.find与string.match功能有何差异?

2026-06-05 11:443阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计641个文字,预计阅读时间需要3分钟。

Lua中string.find与string.match功能有何差异?

我尝试了理解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。

阅读全文

本文共计641个文字,预计阅读时间需要3分钟。

Lua中string.find与string.match功能有何差异?

我尝试了理解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。

阅读全文