So I'm trying to make a program that decodes a string value, to find certain blocks of text and do things with it. I'm having but one problem, and I feel like it's easy and I'm just missing something. Here are my attempts:
local Source = "Testing <hello world> Ended message 1 <test 2> Ended second message" local function CompileText(fromSource) for s in string.gmatch(fromSource, "<[%a%s%p%d]+>") do print(s) -- should print '<test 2>' and '<hello world> ' on TWO different lines end end CompileText(Source)
So basically, I'm trying to make it so that the for loop will run for each <text> block that exists, but for some reason it just prints the entire line of text, even though there are two <text> formatted codes in the string (<hello world> and <test 2>).
I put the [%a%s%p%d]+ in the string pattern so that text in between the < > symbols won't be ignored, or interfere with the process (it'll just be normal text). This is what I'm trying to get it to print:
<hello world>
<test 2>
If anyone could help me with this, I'd be very grateful.
The problem is that <blah> blah blah <blah>
matches your pattern -- it begins with <
and ends with >
and the middle is made of only spaces , letters
[blah]
and punctuation [><]
.
One way to fix that is to use -
instead of +
-- this makes Lua match as few characters as possible, instead of as many.
Perhaps a better way is to not use <[%a%s%p%d]+>
but instead to use <[^>]+>
-- everything except the character ">"
can be inside, which is much closer to the pattern you yourself use when you parse things like this when you read. >
must mean the end, so make it so!