Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse csv using lua script

Tags:

regex

csv

lua

I have a csv file that has data like this:

+12345678901,08:00:00,12:00:00,1111100,35703,test.domain.net
+12345678901,,,0000000,212,test.domain.net

I'm trying to write lua code that will loop through each line, and create an array of values like this:

local mylist = {}
for line in io.lines("data/dd.csv") do
        local id, start, finish, dow, int, domain = line:match("(+%d+),(%d*:*),(%d*:*),(%d*),(%d*),(%a*.*)")
        mylist[#mylist + 1] = { id = id, start = start, finish = finish, dow = dow, int = int, domain = domain}
        print(mylist[#mylist]['id'])
end

The problem is that when the code hits a line that has empty values for start and finish, the regex fails and all fields are nil.

I thought using the * meant 0 or more... I can't seem to find my error / typo.

Thanks.

like image 328
Happydevdays Avatar asked Sep 24 '26 05:09

Happydevdays


2 Answers

This pattern works for me:

"(.-),(.-),(.-),(.-),(.-),(.-)$"
like image 101
lhf Avatar answered Sep 26 '26 22:09

lhf


It seems that you just need to group the digits and : inside a [...]:

match("(%+%d+),([%d:]*),([%d:]*),(%d*),(%d*),(.*)")
        ^       ^^^^^^   ^^^^^^     

Now, the [%d:]* matches zero or more digits or : symbols. Your pattern did not find the match because %d*:* matched 0+ digits followed with 0+ : symbols, and you had more than 1 such sequence.

Also, you need to escape the first + to make sure it matches a literal +.

See online Lua demo

like image 38
Wiktor Stribiżew Avatar answered Sep 26 '26 22:09

Wiktor Stribiżew