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

编程入门 行业动态 更新时间:2024-10-23 06:25:39
本文介绍了在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-29 04:01:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/747785.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Lua   string   gmatch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!