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

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

好吧,你可以选择字母'[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

你可以试试这个:

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中并不总是可行的,它们是相当有限的(没有分组(。

最新更新