Lua string.match()

字符匹配.jpg

前言#

今天我们再一起看一个string家族的匹配函数,它不同于函数string.find()要返回匹配字符的索引,也不同于string.gmatch()函数会返回一个迭代函数可以取到所有的匹配项,这个函数它仅仅范回第一个匹配,简单易用,往往在一些实际应用中找到第一个匹配就够了,我们一起来看一下用法。


string.match()##

  • 原型:string.match(s, pattern [, init])
  • 解释:在字符串s中查找满足参数pattern的匹配子串,如果找到了一个匹配就返回这个匹配子串,若没找到则返回nil,如果参数pattern没有指定匹配参数,则返回整个匹配字符串——"If pattern specifies no captures, then the whole match is returned."(这一句我翻译的不太靠谱啊,有问题麻烦大家给我指正一下),另外,一个数字形参数init用来指定查找字符串的其实位置,这个参数默认为1,当然也可以设置为负数,即-n表示从字符串尾部向前数n个字符开始查找。

Usage##

  • 首先新建一个文件将文件命名为matchtest.lua然后编写如下代码:
local sourcestr = "ehre99wj=--=-*-/4mdqwl\0ds123fef"
print("\nsourcestr = "..sourcestr)

local match_ret = string.match(sourcestr, "%d%d%d")
print("\nmatch_ret is "..match_ret)

match_ret = string.match(sourcestr, "%d%a%a")
print("\nmatch_ret is "..match_ret)

match_ret = string.match(sourcestr, "")
print("\nmatch_ret is "..match_ret)

match_ret = string.match(sourcestr, "%d%d")
print("\nmatch_ret is "..match_ret)

match_ret = string.match(sourcestr, "%d%d", 10)
print("\nmatch_ret is "..match_ret)
  • 运行结果
string_match.png

总结#

  • 由第一组结果可以看出string.match()在遇到\0时不会停止查找,而是一直查找到字符串结尾。
  • 最后两组结果对比可以发现参数init的作用,他指定了搜索匹配的起始位置。
  • 这一篇中有一个关于官方文档的翻译的疑惑,就是"If pattern specifies no captures, then the whole match is returned.",我总感觉我怎么翻译都不太对,麻烦明白的大神给我讲一下是什么意思,其实给我举个例子就明白了。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,671评论 19 139
  • 在挖掘分析的过程当中对字符串的处理是极为重要的,且出现也较为频繁,R语言作为当前最为流行的开源数据分析和可视化平台...
    果果哥哥BBQ阅读 11,190评论 0 8
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 8,472评论 0 4
  • re模块手册 本模块提供了和Perl里的正则表达式类似的功能,不关是正则表达式本身还是被搜索的字符串,都可以...
    喜欢吃栗子阅读 9,481评论 0 13
  • string库提供了字符串处理的通用函数。 例如字符串查找、子串、模式匹配等。 当在 Lua 中对字符串做索引时,...
    chiguozi阅读 9,432评论 0 3