首页 > 解决方案 > 如何在lua中用多个字符分隔字符串?

问题描述

字符串为“abc||d|ef||ghi||jkl”,如果分隔符为“||”,如何将此字符串划分为数组 . 例如。“abc”,“d|ef”,“ght”,“jkl”。

我找到了一个分割字符串的代码,但是只能使用一个字符作为分隔符。代码是:

text={}
string="abc||d|ef||ghi||jkl"

for w in string:gmatch("([^|]*)|")
do 
  table.insert(text,w) 
end

for i=1,4
do
   print(text[i])
end

因此,如何分隔多个字符的字符串?

标签: stringlua

解决方案


你可以试试这个:

text={}
string="abc||def||ghi||jkl"

for w in string:gmatch("([^|]*)||")
do 
  table.insert(text,w) 
end

for i=1,4
do
   print(text[i])
end

这是相同的代码,只是多了一个“|”。

编辑:

这现在应该更好地工作:

str = "abc||d|ef||ghi||jkl"

function getMatches(inputString)
    
    hits = {}
    
    beginSection = 1
    
    consecutive = 0
    
    for index=0,#inputString do
        chr = string.sub(inputString,index,index)
        if chr=="|" then
            consecutive = consecutive+1
            if consecutive >= 2 then
                consecutive = 0
                table.insert(hits,string.sub(inputString,beginSection,index-2))
                beginSection = index + 1
            end
        else
            consecutive = 0
        end
    end
    
    if beginSection ~= #inputString then
        table.insert(hits,string.sub(inputString,beginSection,#inputString))
    end
    
    return hits
end

for _,v in pairs(getMatches(str)) do print(v) end

io.read()

模式并不总是在 Lua 中使用的方式,它们相当有限(没有分组)。


推荐阅读