程序员首页投稿(暂停使用,暂停投稿)

Lua string.gmatch()

2016-08-12  本文已影响14004人  AlbertS
寻找匹配.png

前言#

今天来看一个高端的匹配函数,高端在哪里呢?它比较像正则表达式,但是为了保持Lua小巧的特点有没有用正则表达式那一套,单从功能上来说这个函数的模式匹配没有正则表达式那么强大,但是就它的实现代码来说他已经相当强大了,基本满足日常的编程需求,接下来我们一起来看一下它的使用方法。

内容#


string.gmatch()##


Usage##

local str = "12ab34,eed,56"
local func_itor = string.gmatch(str, "%d+")

-- 查看func_itor类型
print("func_itor is", func_itor)

-- 第一次调用函数func_itor
print("func_itor ret is ", func_itor())

-- 再次调用函数func_itor
print("func_itor ret is ", func_itor())

-- 使用循环来打印
local sourcestr = "hello world from Lua"
local index = 1
print("\noutput capture using loop:")
for word in string.gmatch(sourcestr, "%a+") do
    print(index, word)
    index = index + 1
end

-- 查找属性对
local attrstr = "from=world, to=Lua, name=AlbertS"
print("\noutput attr pair capture using loop:")
for k,v in string.gmatch(attrstr, "(%w+)=(%w+)") do
    print(k, v)
end

local nonumstr = "fadfasd,.;p[];'asd"
local func_numitor = string.gmatch(nonumstr, "%d+")
local numret = func_numitor()
print("\nnumret ret is", numret)
string_gmatch.png

总结#

上一篇 下一篇

猜你喜欢

热点阅读