regexluastring-matchinglua-patternslua-5.1

Include empty matches when using string.gmatch to split a string in lua 5.1


I have a comma seperated input string that needs to support empty entries. So a string like a,b,c,,d should result in a table with 5 entries, where the 4'th is an empty value.

A simplified example

str="a,b,c,,d"
count=0

for v in string.gmatch(str, '([^,]*)') do
    count = count + 1
end

print(count)

This code outputs

9

in Lua 5.1, although there are only 5 entries.

I can change the * in the regex to + - then it reports the 4 entries a,b,c,d but not the empty one. It seems that this behaviour has been fixed in Lua 5.2, because the code above works fine in lua 5.2, but I'm forced to find a solution for lua 5.1

My current implementation

function getValues(inputString)
  local result = {}

  for v in string.gmatch(inputString, '([^,]*)') do
    table.insert(result, v)
  end

  return result
end

Any suggestions about how to fix?


Solution

  • You may append a comma to the text and grab all values using a ([^,]*), pattern:

    function getValues(inputString)
      local result = {}
    
      for v in string.gmatch(inputString..",", '([^,]*),') do
        table.insert(result, v)
      end
    
      return result
    end
    

    The output:

    a
    b
    c
    
    d