我只想將字串拆分一次,因此輸出如下所示:
STRING1: STRING.STRING1.STRING2
OUT1: STRING
OUT2: STRING1.STRING2
我試圖制作一個函式,因為我找不到其他人制作的函式,而且它有點奏效。出于某種原因,如果您將分隔符設定為"."那么該函式將完全停止作業并將默認開始和結束值設定為1, 1因此我當前的輸出是:
STRING1: STRING.STRING1.STRING2
OUT1:
OUT2: TRING.STRING1.STRING2
有誰知道我在這個函式中做錯了什么:
function splitOnce(inputstr, sep)
local s, e = inputstr:find(sep)
local t = {}
--print(inputstr)
--print(sep)
--print("start: "..tostring(s)..", end: "..tostring(e))
table.insert(t, inputstr:sub(1, s - 1))
table.insert(t, inputstr:sub(e 1, -1))
return t
end
uj5u.com熱心網友回復:
您可以使用match使用具有 2 個捕獲的模式來分隔字串。在這里,我使用(.-)%".. sep .."(. )where.-將在分隔符之前捕獲盡可能短的字串,并. 在它之后捕獲所有剩余的字串。
這種方法的一個限制是單獨被轉義,所以如果你使用一個單獨的,例如d,w或者另一封信是一個神奇字符在拍打它不會按預期方式作業,它應該對所有單個字符標點符號分隔符的作業,雖然。
function splitOnce(inputstr, sep)
local prefix, suffix = inputstr:match("(.-)%".. sep .."(. )")
local t = {}
print(inputstr)
print(sep)
print("prefix: "..tostring(prefix)..", suffix: "..tostring(suffix))
table.insert(t, prefix)
table.insert(t, suffix)
return t
end
splitOnce("STRING.STRING1.STRING2", ".")
輸出
STRING.STRING1.STRING2
.
前綴:STRING,后綴:STRING1.STRING2
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376156.html
