如何在lua中使用多个分隔符拆分字符串? [英] How do I split a string with multiple separators in lua?

查看:529
本文介绍了如何在lua中使用多个分隔符拆分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个字符串拆分成一个由多个定界符分隔的数组.

I want to split a string into an array divided by multiple delimiters.

local delim = {",", " ", "."}
local s = "a, b c .d e , f 10, M10 , 20,5"

结果表应如下所示:

{"a", "b", "c", "d", "e",  "f", "10", "M10", "20", "5"}

分隔符可以是空格,逗号或点. 如果两个分隔符(例如,空格和逗号)紧挨着,则应将它们合拢,否则应忽略其他空格.

Delimiters can be white spaces, commas or dots. If two delimiters like a white space and comma are coming after each other, they should be collapsed, additional whitespaces should be ignored.

推荐答案

此代码通过构建定界符集补码的模式按需拆分字符串.

This code splits the string as required by building a pattern of the complement of the delimiter set.

local delim = {",", " ", "."}
local s = "a, b c .d e , f 10, M10 , 20,5"
local p = "[^"..table.concat(delim).."]+"
for w in s:gmatch(p) do
        print(w)
end

调整代码以将单词"保存在表中.

Adapt the code to save the "words" in a table.

这篇关于如何在lua中使用多个分隔符拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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