在 Lua 中使用 string.gmatch() 拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19907916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:10:18  来源:igfitidea点击:

Split a string using string.gmatch() in Lua

stringlualua-patterns

提问by Niccolo M.

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

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

I have the following string:

我有以下字符串:

local s = "one;two;;four"

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

我想将其拆分为";". 我想,最终,去得到{ "one", "two", "", "four" }回报。

So I tried to do:

所以我尝试这样做:

local s = "one;two;;four"

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

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

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

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.

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

回答by Yu Hao

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

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).

通过;在字符串末尾添加一个额外的字符串,该字符串现在变为"one;two;;four;",您想要捕获的所有内容都可以使用该模式"([^;]*);"进行匹配:任何;后面没有a ;(贪婪)的内容。

Test:

测试:

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

Output:

输出:

1: one
2: two
3:
4: four

回答by han xi

function split(str,sep)
    local array = {}
    local reg = string.format("([^%s]+)",sep)
    for mem in string.gmatch(str,reg) do
        table.insert(array, mem)
    end
    return array
end
local s = "one;two;;four"
local array = split(s,";")

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

result:

结果:

1:one

1:一个

2:two

2:两个

3:four

3:四