lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, Feb 10, 2018 at 1:30 AM, Egor Skriptunoff
<egor.skriptunoff@gmail.com> wrote:
> On Sat, Feb 10, 2018 at 4:18 AM, Paul K wrote:
>>
>>
>> One case it doesn't handle is the mix of ' and " in the string (as the
>> string should only be closed with the same quote is was opened with,
>> assuming both " and ' are allowed).
>>
>> This code should handle this case (also added examples):
>>
>> local list = {
>>   '123,"ABC, DEV 23",345,,202,NAME',
>>   ',"ABC, DEV 23",345,534,202,NAME',
>>   '123,"ABC, DEV 23",345,534.202,',
>>   '123 , "ABC, DEV 23" , 345 , 534 , 202 , NAME',
>>   [[123,"ABC, \"he,llo\", DEV 23",,,,NAME]],
>>   [[123,"ABC, \\",llo\", DEV 23,,,,NAME]],
>>   [[123,'ABC, "hel,lo", DEV 23',342,534,202,NAME]],
>>   [[123,"ABC, 'hel,lo, DEV 23",342,534,202,NAME]],
>> }
>> local escaped, instring, pos, start = false, false, -1, ""
>> for _,s in ipairs(list) do
>>   s = s:gsub([[()(["',\\])]], function(p, s)
>>       if p > pos+1 then escaped = false end
>>       if s == '\\' then escaped, pos = not escaped, p end
>>       if (s == '"' or s == "'") and not escaped
>>       and (not instring or s == start) then instring, start = not
>> instring, s end
>>       if s == ',' and not instring then s = '~' end
>>       return s
>>     end)
>>   print(s)
>> end
>>
>
> Exactly the same could be done using Lua patterns:
>
> for _,s in ipairs(list) do
>   s = s:gsub("\\?.", {['"']='\0\0"', ["'"]="\0\0'", [","]="\0,"})
>        :gsub("((%z%z.).-)%2", function(a,b) return a:gsub("%z,", ",")..b
> end)
>        :gsub("%z,", "~")
>        :gsub("%z", "")
>   print(s)
> end

Ugh, I'm so intellectually lazy I had to read your answers. (rolling
of eyes at myself). This is where I was going with it last night but
couldn't figure it out. I agree with Martin that it's not very pretty.

Russ