在 Lua 中使用 string.gmatch() 拆分字符串 [英] Split a string using string.gmatch() in Lua

查看:38
本文介绍了在 Lua 中使用 string.gmatch() 拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一些讨论和实用函数,用于拆分字符串,但我需要一个临时单行程序来完成一个非常简单的任务.

There are some discussions here, and utility functions, for splitting strings, but I need an ad-hoc one-liner for a very simple task.

我有以下字符串:

local s = "one;two;;four"

我想在 ";" 上拆分它.我最终想要得到 { "one", "two", "", "four" } 作为回报.

And I want to split it on ";". I want, eventually, go get { "one", "two", "", "four" } in return.

所以我尝试这样做:

local s = "one;two;;four"

local words = {}
for w in s:gmatch("([^;]*)") do table.insert(words, w) end

但结果(words表)是{ "one", "", "two", "", "", "four", "" }.那当然不是我想要的.

But the result (the words table) is { "one", "", "two", "", "", "four", "" }. That's certainly not what I want.

现在,正如我所说,这里有一些关于拆分字符串的讨论,但它们中有冗长"的函数,我需要一些简洁的东西.我需要这段代码用于展示 Lua 优点的程序,如果我添加一个冗长的函数来做一些如此微不足道的事情,它就会对我不利.

Now, as I remarked, there are some discussions here on splitting strings, but they have "lengthy" functions in them and I need something succinct. I need this code for a program where I show the merit of Lua, and if I add a lengthy function to do something so trivial it would go against me.

推荐答案

local s = "one;two;;four"
local words = {}
for w in (s .. ";"):gmatch("([^;]*);") do 
    table.insert(words, w) 
end

通过在字符串末尾多加一个;,字符串现在变成了"one;two;;four;",你想捕捉的一切都可以使用要匹配的模式 "([^;]*);":任何不是 ; 的东西,后跟 ;(贪婪).

By adding one extra ; at the end of the string, the string now becomes "one;two;;four;", everything you want to capture can use the pattern "([^;]*);" to match: anything not ; followed by a ;(greedy).

测试:

for n, w in ipairs(words) do
    print(n .. ": " .. w)
end

输出:

1: one
2: two
3:
4: four

这篇关于在 Lua 中使用 string.gmatch() 拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆