My string pattern doesn't work

I am trying to make string pattern to get any strings in a string. An example is Hello there "this is", "a test" Where it should recognize "this is" and "a test" as two seperate strings. My current pattern I made is (['"])([^\n%1]*)%1 . But it does not yield the result I am expecting. I am doing string.match(s, pattern) and that returns a tuple: " and this is", "a test . Does anybody know how I could fix this?

Hey there!

Here’s a piece of code that does the job:

local str = 'Hello there "this is", "a test"'
local strings = {}
local current = ""
local open = false
local char
for i=1,#str do
	char = string.sub(str,i,i)
	if open == true then
		current = current .. char
		if char == '"' then
			open = false
			table.insert(strings,current)
			current = ""
		end
	elseif char == '"' then
		open = true
		current = current .. char
	end
end
print(strings)

It probably does alot of things inefficiently, but it’s the best I could think of.

1 Like

I appreciate the answer, but I am trying to do this with patterns and matching

local input = 'Hello there "this is", "a test"'
local pattern = '(["\'])(.-)%1'

for quote, match in string.gmatch(input, pattern) do
  print(match)
end

1 Like

This works perfectly, thank you!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.