How do you use string.match?

Im trying to implement search into a gui, how do you use string.match?
I looked at the documentation, but i dont understand it.

Think of a person looking through each letter in a sentence. It will look for patterns based off of what pattern you input into it(2nd arg)

i know how it works, i just dont know how to use it.

Its a specific use case. Not something used very often but cool.

string.match() can be used to find a specific string pattern you’re looking for, it’s a unique way of checking what you want to search for

There are 3 parameters for using string.match():

  • Parameter 1: The string you want to search for inside Parameter 2

  • Parameter 2: The string pattern to detect

  • Parameter 3: (Optional) A number value specifying where to first start the search

A cool example would be is to use this:

local RadarSearch = string.match("BeepBeepBeepBeepCookieBeepBeep", "Cookie")
print(RadarSearch) --Cookie

We’re attempting to find a Cookie inside this specific string here, if we found the Cookie then it’s returned as “Cookie”! But say there’s no cookie:

local RadarSearch = string.match("BeepCakeBeepBeepChocolateBeepOnion", "Cookie")
print(RadarSearch) --nil

This would return back nil, since there’s no “Cookie” located inside the String we want to search for

You can basically use string.match() for attempting to find a pattern inside the string you’re searching for, and it’ll either return back as 2 values:

  • nil if there’s no pattern inside the string

  • The string pattern you searched for

4 Likes