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