How do I make string.gsub match the closest enclosing characters instead of the first found and last found characters?

I am writing a formatting function to replace %Variable% with the corresponding variable, and it works unless two variables are in the same string together. Lets say the input is %cats% and %catsTwo%.
(this is the function I am using)

table.pack(str:gsub("%%(.+)%%", function (var) print(var,"SEG") if vars[var] then return vars[var] else return "%"..var.."%" end end))

And what that input prints is cats% and %carsTwo SEG, meaning the string.gsub only replaced the first and last percentage sign. Or maybe this isnt true and the question should be worded differently. tldr I need help with string manipulation

I figured out I could just do %%([%w%p]+)%% as the regex because variables dont contain spaces.

local strings = "%cats% and %catsTwo% and %_catsThree%"

for match in strings:gmatch("%%([%w_]+)%%") do

:gmatch() is great for variable matches (when it is possible for 1 or more matches to be found).

1 Like