在Lua中使用string.gmatch()拆分字符串 [英] Split a string using string.gmatch() in Lua
问题描述
这里有一些讨论和实用程序功能,用于拆分字符串,但是我需要一个临时的单层衬纸来完成一个非常简单的任务.
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"
我想在";"
上拆分它.我希望最终得到get { "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屋!