Split a string but ignore when within quotes

This is one of the first use cases I’ve found for the %bxy modifier.

1 Like

Wait, benchmark mine compared to yours for you, because for me it seems like mine is faster??

local function GetParameters(String)
	local Substrings = {}

	local function Substitution(Substring)
		table.insert(Substrings, Substring)
		return ""
	end
	
	String = string.gsub(String, '%b""', Substitution)
	String = string.gsub(String, '%w+', Substitution)

	return Substrings
end

local Time = os.clock()

for _ = 1, 1000 do
	GetParameters('Hello1 "Hello2 Hello3" Hello4 "Hello 5 "')
end

print(os.clock() - Time) --0.0009382000134792179
1 Like

Since I noticed %bxy gotta add on to this:

Balanced capture is fun for writing custom parsers, such as for json or the like.
Also useful if you’re like me and enjoy making useless things such as a custom scripting language. Made one a few years ago.

1 Like