How do I look for patterns in a string?

So what i want to make is a script that can look for patterns in a string. For example: “fghjfghjfghj” the pattern here is fghj. does any have any idea of how i can achieve this. Thanks.

Are you trying to look for patterns dynamically, in other words is the string unknown at compile time?

local function FindPattern(String)
	for Count = 2, string.len(String) / 2 do
		local Substrings = {}
		for Index = Count, string.len(String), Count do
			table.insert(Substrings, string.sub(String, Index - Count + 1, Index))
		end

		local State = true
		for Index, Substring in ipairs(Substrings) do
			if Substring ~= Substrings[1] then State = false break end
		end
		if State then return Substrings[1] end
	end
end

local Pattern = FindPattern("fghjfghjfghj")
print(Pattern) --fghj
Pattern = FindPattern("abcdeabcdeabcde")
print(Pattern) --abcde

im looking for them dynamically. i dont get the second question because im only a ui designer. if you can break down what’s happening in the script i’ll understand better probably.

Note: The word “string” is referring to text.

Functions used in this code snippet:

string.len() -- returns the amount of characters in a given string. (string.len('LOL') would return 3)
string.sub() -- removed a part of a string. i.e turning "Hello World!" > "Hello", cutting off "World!"

It’s essentially getting all the characters in a string in pairs of two, and comparing each pair.

So for example: “xdxdxdxdxd” split the string in pairs of two and add them into a table, now we get
{xd, xd, xd, xd, xd}, now we check everything in the table and check if there is a match (which there are), then if there is a match we return said match (which is “xd”).

Best to read this for a move in depth explanation of the functions being utilized here:

Okay thanks a lot for explaining!