如何在 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

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

点赞
用户3342050
用户3342050

好的,你可以选择抓取字母'[a-zA-Z]+'或者'[%a]+'

#! /usr/bin/env lua
text = {}
string = 'abc||def||ghi||jkl'

for w in string:gmatch('[a-zA-Z]+') do
    table.insert(text, w)
end

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

或者选择任何不是管道的字符'[^|]+'

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

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

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

https://riptutorial.com/lua/example/20315/lua-pattern-matching

abc

def

ghi

jkl

2021-07-04 05:40:58
用户14091631
用户14091631

你可以尝试这个:

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

这是同样的代码,只是加了一个 "|"。

EDIT:

现在这个代码应该更好用:

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中并不总是行之有效,它们相对有限(没有分组)。

2021-07-08 04:34:48