Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get columns from CSV as regex groups

Tags:

regex

Not used to play a lot with regex, but now its really causing me a headache.

I have a multi line CSV file where I need to find a line which starts with a specific value in the first field and then have the groups for all the remaining fields of that line even if some fields are empty. The length of the CSV could variate

So for example:

monday,1,8,nice,,sunny,cold,
tuesday,3,2,hello,bye,,sad,tomorrow,
wednesday,8,ok,4,xxx,,999,welcome,

I want to match the CSV line which starts with "tuesday" and have all the fields excluding the first one matching groups so:

Group1 = 3
Group2 = 2
Group3 = hello
Group4 = bye
Group5 = 
Group6 = sad
Group7 = tomorrow

Unfortunately I am stuck to regex because the tool only handles regex. Parsing it with a few lines of code in Go would be much easier, but its simply not possible in this situation.

Found some help on IRC group, it works but only with a fixed length CSV string:

^tuesday,([^,]+),([^,]+),([^,]+),([^,]+),([^,]*),([^,]+),([^,]+),$

Could it be done with a variable length as well?

Thanks

like image 979
snowbird Avatar asked Oct 20 '25 13:10

snowbird


1 Answers

If the number of columns is fixed then this will work:

^tuesday,([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),([^,]*)

It finds lines that start with tuesday and creates 7 groups that catches everything that is not a ,.

You can check it here: https://regexr.com/3pn81.

like image 58
mx0 Avatar answered Oct 23 '25 02:10

mx0