How to get string between strings one way only?

I want to get all the strings between <var> and </var>. I’ve tried this code
(Text is hi <var>test</var> <var>test2</var>)

local var = string.match(Text,'<var>(.+)</var>')

This works but only when <var> and </var> are only found in the Text string once. When there are multiple occurances it returns this.
image
When I want it to return this:
test test2
I think this is because it returns all the strings between <var> and </var> but it also returns the strings between </var> and <var>. I only want it to return the strings between <var> and </var>, not the other way round. How would I achieve this?

string.split?

30charlimit

If i used string.split it would also return text outside of <var> and </var>

Try doing it but missing a letter at the start and end, like string.split(Text, 'var>(.+)</var') so that if it doesn’t contain any > or < in the split, it’s inbetween the tags

Try using (.-) instead of (.+) to match the shortest occurrence

1 Like
local str = "<var>test</var> <var>test2</var>"
for sub in string.gmatch(str, "<var>([^<>]*)</var>") do
	print(sub)
end

--test
--test2
2 Likes

What if they wanna use angle brackets inside the tag string tho? :laughing:

The problem with the .- pattern is nested tags.

local str = "<var><var>test</var></var> <var>test2</var>"
for sub in string.gmatch(str, "<var>(.-)</var>") do
	print(sub)
end

--<var>test
--test2
local str = "<var><var>test</var></var> <var>test2</var>"
for sub in string.gmatch(str, "<var>([^<>]*)</var>") do
	print(sub)
end

--test
--test2