Help with string.gmatch and string.match

Hello, i’m learning lua could someone explain to me how to use these two functions, please? :frowning:

string.gmatch() -- How to use?
string.match() -- How to use?

I would appreciate very much if someone could explain them to me, they are the ones that I still have to learn. :smiley:

3 Likes

They use string patterns, which is similar to regular expressions. I used https://regexone.com/ to learn, but it needs to be adapted a little for Lua. They are very powerful functions though.

Match will get one or more matching patterns that you search for. For example, “%w+” matches a full word, but that’s something you will need to learn with string patterns.

gmatch works like pairs. For example, if you wanted to loop over every word in a string, do this.

for word in string.gmatch("Example sentence with like six words", "%w+") do
    print(word)
end

That will print all the words.

3 Likes

gmatch returns an iterator function that - when given a pattern - captures and returns it.
For example, if you wanted to get all numbers within a string, you could do

local Str = "123abc456def"
local Nums = {}
for Num in Str:gmatch("%d+") do -- %d being the pattern for numbers, + being 1 or more within the capture
    table.insert(Nums, Num)
end
print(table.unpack(Nums)) -- 123 456

As for match, it captures a pattern within a string, and can return them.
For example

local Str = "Hello World!"
local Str1, Str2 = Str:match("(.+) (.+)") -- . being any character, + being 1 or more character within the capture, () being the capture group
print(Str1) -- Hello
print(Str2) -- World!

There’s a page on the devhub about the various patterns known as the String Patterns (roblox.com) page if you wish to learn more about them.

I hope this helped :slight_smile:

14 Likes

Thanks you a lot guys! :smiley: :smiley:

2 Likes