This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Zacherl1990's profile picture

String.gmatch With Multiple Captures But Without Key Value Pairs?

Started by Zacherl1990, 24 November 2013 - 09:53 AM
Zacherl1990 #1
Posted 24 November 2013 - 10:53 AM
Hey there,

i'm trying to extract two substrings of a given string with string.gmatch(). This is my current code:
local s = "::hook::123:blabla"
local d = string.gmatch(s, "::hook::(/>%d+):(/>.+)")
for k in d do
  print(k)
end

But the output is just "123". The "blabla" part does not get printed.

If i try this:
local s = "::hook::123:blabla"
local d = string.gmatch(s, "::hook::(/>%d+):(/>.+)")
for k, v in d do
  print(k .. ":" .. v)
end

the output is "123:blabla", but it's grouped into key value pairs, what does not look right to me.

Is there a way to extend the first code for the second pattern to be included?

Edit: The "/>" is not part of my regex. Seems to be an error with this vBulletin code plugin :D/>

Best regards
Zacherl
Edited on 24 November 2013 - 11:04 AM
MKlegoman357 #2
Posted 24 November 2013 - 12:48 PM
You are using the wrong function. string.gmatch() returns an iterator function (for use in for loops) which will return all occurrences of a pattern in the given string:


local myText = "This is a normal sentence."

for word in string.gmatch(myText, "%w+") do
  print(word)
end

This code would output:


This
is
a
normal
sentence

You would want to use string.match(). It returns one or more match from a string:


local myString = "LEGO: Hello!"

local nickname, message = string.match(myString, "(%w+): (.+)")

print("Nickname: " .. nickname)
--> Nickname: LEGO

print("Message: " .. message)
--> Message: Hello!

Notice these parenthesis around (%w+) and (.+)? This means that it only returns matches in those parenthesis and it will return them as multiple variables.

PS: In Lua it's called pattern not regex.

EDIT:
the output is "123:blabla", but it's grouped into key value pairs, what does not look right to me.

As I said before it returns an iterator function. When you do your for loop you actually give it an iterator function returned by string.gmatch(). An iterator function is a function which - when called - will return some values. At some point it will return nil. for loop calls that function over and over again as long as it doesn't return nil. When it returns nil - for loop stops.
Edited on 24 November 2013 - 12:03 PM
Zacherl1990 #3
Posted 24 November 2013 - 06:42 PM
Aw you are right, i was using the wrong function. Thank you!