Lua - 字串分割



字串分割是指我們傳遞一個正則表示式或模式,可以使用該模式將給定字串分割成不同的部分的過程。

在 Lua 中,標準庫中沒有內建的 split 函式,但我們可以使用其他函式來完成 split 函式通常執行的工作。

Lua 中一個非常簡單的 split 函式示例是使用 **gmatch()** 函式,然後傳遞我們希望根據其分割字串的模式。

示例

請考慮以下示例:

main.lua

local example = "lua is great"
for i in string.gmatch(example, "%S+") do
   print(i)
end

輸出

lua
is
great

以上示例對於簡單的模式可以正常工作,但當我們想要使用正則表示式,並且我們可以使用預設模式進行分割時,我們可以考慮一個更優雅的示例。

示例

請考慮以下示例:

main.lua

function mysplit (inputstr, sep)
   if sep == nil then
      sep = '%s'
   end
   local t={}
   for str in string.gmatch(inputstr, '([^'..sep..']+)') 
   do
      table.insert(t, str)
   end
   return t
end
ans = mysplit('hey bro whats up?')
for _, v in ipairs(ans) 
do 
   print(v) 
end
ans = mysplit('x,y,z,m,n',',')
for _, v in ipairs(ans) 
do 
   print(v) 
end

輸出

hey
bro
whats
up?
x
y
z
m
n
廣告

© . All rights reserved.