Home > Mobile >  Split once function in lua
Split once function in lua

Time:12-08

I want to split a string only once so the output looks like this:

STRING1: STRING.STRING1.STRING2

OUT1: STRING
OUT2: STRING1.STRING2

I tried to make a function since I can't find a function that someone else made, and it kind of worked. For some reason, if you set the separator to "." then the function completely stops working and sets the default start and end values to 1, 1 Because of this my current output is:

STRING1: STRING.STRING1.STRING2

OUT1: 
OUT2: TRING.STRING1.STRING2

Does anyone know what I'm doing wrong in this function:

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

CodePudding user response:

You can use match to separate the string using a pattern with 2 captures. Here I use (.-)%".. sep .."(. ) where .- will catch the shortest possible string before the separator and . will catch everything left after it.

One limitation of this method is the separate is escaped, so if you use a separate such as d, w, or another letter that is a magic char in a patter it will not work as expected, it should work for all single char punctuation separators though.

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", ".")

output

STRING.STRING1.STRING2

.

prefix: STRING, suffix: STRING1.STRING2

  • Related