string - 如何在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
因此,如何分隔多个字符的字符串?
解决方案
你可以试试这个:
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 中使用的方式,它们相当有限(没有分组)。
推荐阅读
- typescript - Nuxt TypeScript 错误:nuxt:typescript 找不到模块'@/my-module'
- node.js - 如何在nodejs的控制器内调用multer中间件?
- facebook - PSID 不支持 GET 请求 Graph API?
- xpath - c# html agility pack 从 html 源代码中提取字符串
- reactjs - REACT 导入 css 和 js 文件
- c# - .NET 中是否存在等效的 Trie 数据结构?
- ios - 如何在swiftui中处理RotationGesture的角度
- pyspark - 如何从文本中查找数字
- macos - 无法启动 DAML 工作室
- python-3.x - 以下代码的 Python GUI TKINTER SQLITE3 错误