str = "cat,dog,,horse"
for word in string.gmatch(str, "([^,'',%s]+)") do
print(word)
end
This code outputs the following.
cat
dog
horse
I want to consider nil entry as well and want to have the following output.
cat
dog
nil
horse
How can this be done? Could someone please point out?
A few things:
nil ~= "". You probably want the empty string rather than nil here. It is however trivial to convert one into the other, so I'll be using the empty string in the following code.gmatchpattern. If there are no "captures" (parentheses), the entire pattern is implicitly captured.'and,twice in the character class; just once suffices. I'll be assuming you want to split by,.The issue is that currently your pattern uses the
+(one or more) quantifier when you want*(zero or more). Just using*works completely fine on Lua 5.4:However, there is an issue when you try to run that same code on LuaJIT: It will produce seemingly random empty strings rather than only producing an empty string for two consecutive delimiters (this could be seen as "technically correct" since the empty string is a match for
*, but I see it as a violation of the greediness of*). One solution is to require each match to end with a delimiter, appending a delimiter, and matching everything but the delimiter:A third option would be to split manually using repeated calls to
string.find. Here's the utility I wrote myself for that:The usage in this example would be
Whether you want to add this to the
stringtable, keep it in a local variable or perhaps arequired string util module is up to you.