Help with string patterns

Hi, I’m new to string patterns and I want to use string.split to separate a string at a given pattern.

For example, I want to split the string "156J711111e3331443211" at any alphabetical character, upper or lower case. The string patterns reference page says to use "%a" to target all uppercase or lowercase letters.

My goal output:

1 156
2 711111
3 3331443211

The actual output:

1 156J711111e3331443211

The code:

for i,v in pairs(string.split("156J711111e3331443211", "%a")) do 
    print(i,v) 
end

Knowing how to do this would help me with string patterns far beyond just this instance. Thanks in advance.

Unfortunately string.split doesn’t allow for string patterns. I have a feature request to support this, if you want to support it.

Now, more along the lines of the spirit of your inquiry, you would want to make your own function instead.

local function split(str, delimiter)
    local strings = { }

    for occurrence in str:gmatch("[^" .. delimiter .. "]") do
        table.insert(strings, occurrence)
    end
    return strings
end
1 Like

Hm, weird that not all the string functions are able to use string patterns. If string.split did allow for string patterns, would my code work then?

Appreciate the code by the way.

string.split is a part of Luau, so not part of the vanilla standard library. But yes, your code would work if string.split supported patterns