Parsing the source string with inline quotes in a list with lua

Parsing a string by specifying a separator is quite simple. There are many examples. However, I am having problems splitting the original string with embedded double or single quotes:

item1;item2 "x;y;z";item3 args='arg1;arg2;arg3';item4

I want to get the following result when splitting with ;as a separator:

item1
item2 "x;y;z"
item3 args='arg1;arg2;arg3'
item4
+4
source share
2 answers

You can also do this in the “old fashioned” way, i.e. without built-in pattern matching:

function parse(s,target)
  local line = ''
  local quote
  for c = 1,#s do
    c = s:sub(c,c)
    if c == quote then
      quote = nil
    elseif quote == nil and (c == '"' or c == "'") then
      quote = c
    end
    if quote or c ~= target then
      line = line .. c
    else
      print(line)
      line = ''
    end
  end
  print(line)
end

local s = [[item1;item2 "x;y;z";item3 args='arg1;arg2;arg3';item4]]
parse(s,';')
+2
source
local str = [[item1;item2 "x;y;z";item3 args='arg1;arg2;arg3';;item5]]

for part in ('""'..str..';')
   :gsub(
      "((['\"]).-%2)([^'\"]*)",
      function(q, _, u) return q..u:gsub(";", "\0") end)
   :sub(3)
   :gmatch"(%Z*)%z"
do
   print(part)
end
+1
source

Source: https://habr.com/ru/post/1676087/


All Articles