How can I fix my custom string detector script? I'm stumped

Sorry if this is bad code, I know it is and it’s because I’m REALLY confused on how I do this. Also, no, I’m not using string.find() because that won’t work for what I’m doing. I’m trying to make an emoji script that I can’t really describe.
code:

local function Write(Message:string, Box:TextLabel)
	local Images = {
		":BB-5:"
	}
	local FullString = ""
	local ApproximatedEmoji = 0
	local BeginI = 0
	for i, letter in pairs(Message:split("")) do
		if letter ~= "nil" then
			for e, obj in pairs(Images) do
				if obj ~= "nil" and obj ~= nil then
					if obj:split("")[1] == letter and ApproximatedEmoji == 0 then
						ApproximatedEmoji = e
						FullString = letter
						BeginI = i - 1
					end
					local code = obj:split("")[(i - 1) - BeginI]
					if code ~= nil and code ~= "nil" then
						print(letter)
						print(code)
						if ApproximatedEmoji > 0 and code == letter then
							print(code)
							FullString ..= letter
							print(FullString)
							if FullString == obj then
								print(obj)
							end
						end
					end
				end
			end
		end
	end
end

what it’s supposed to do: locate :discord-style emojis: and, if it finds one, print the obj variable (the emoji).
currently, it’s acting very weird and detecting the entire first bit as an emoji.

log 1 (what it is doing):

  20:20:49.380  f  -  Client - LocalScript:109
  20:20:49.380  :  -  Client - LocalScript:110
  20:20:49.380  o  -  Client - LocalScript:109
  20:20:49.381  B  -  Client - LocalScript:110
  20:20:49.381  n  -  Client - LocalScript:109
  20:20:49.381  B  -  Client - LocalScript:110
  20:20:49.381  t  -  Client - LocalScript:109
  20:20:49.381  -  -  Client - LocalScript:110
  20:20:49.381     -  Client - LocalScript:109
  20:20:49.381  5  -  Client - LocalScript:110
  20:20:49.381  c  -  Client - LocalScript:109
  20:20:49.381  :  -  Client - LocalScript:110
  20:20:49.382     -  Client - LocalScript:109
  20:20:49.382  :  -  Client - LocalScript:110
  20:20:49.382  <  -  Client - LocalScript:109
  20:20:49.382  B  -  Client - LocalScript:110
  20:20:49.382  /  -  Client - LocalScript:109
  20:20:49.382  B  -  Client - LocalScript:110
  20:20:49.382  f  -  Client - LocalScript:109
  20:20:49.382  -  -  Client - LocalScript:110
  20:20:49.382  o  -  Client - LocalScript:109
  20:20:49.383  5  -  Client - LocalScript:110
  20:20:49.383  n  -  Client - LocalScript:109
  20:20:49.383  :  -  Client - LocalScript:110
  20:20:54.757  Disconnect from  -  Studio
  20:25:39.810  'Place1' auto-recovery file was created  -  Studio

log 2 (not an actual log) (what it should be doing):

  20:20:49.380  :  -  Client - LocalScript:109
  20:20:49.380  :  -  Client - LocalScript:110
  20:20:49.380  B  -  Client - LocalScript:109
  20:20:49.381  B  -  Client - LocalScript:110
  20:20:49.381  B  -  Client - LocalScript:109
  20:20:49.381  B  -  Client - LocalScript:110
  20:20:49.381  -  -  Client - LocalScript:109
  20:20:49.381  -  -  Client - LocalScript:110
  20:20:49.381  5  -  Client - LocalScript:109
  20:20:49.381  5  -  Client - LocalScript:110
  20:20:49.381  :  -  Client - LocalScript:109
  20:20:49.381  :  -  Client - LocalScript:110
  20:20:54.757  Disconnect from  -  Studio
  20:25:39.810  'Place1' auto-recovery file was created  -  Studio

HOW DO I FIX THIS I’M SO STUMPED???

Sorry I couldn’t follow what exactly you are doing, here
Do you want to detect the text between the colons? i.e :BB-5: would give BB-5 , or are you trying something else.

Unless I’m missing something, why wouldn’t string.find() work for this?
If you’re trying to find patterns for :text_between_colons:, then string.find(str, ":.+:") should work I believe.
If you’re unaware of how string patterns work, . means any character, + mean match 1 or more of this character and colons are just colons, so :.+: should match a string which is in between two colons (including the colons).

I’m looking for every instance of :BB-5: in a string, I want to cut off the text before it is placed, and then I want to add an image in front of the text. I then want to continue the text, knowing exactly when it ended, and I want to do this every time :BB-5: appears.

Well then you still use string.find()

local str = "this is your string"
local pattern = ":BB-5:"

local curIndex = 1
while curIndex <= #str do
    local matchStart, matchEnd = string.find(str, pattern, curIndex)

    local subString = string.sub(str, curIndex, matchStart and matchStart-1) -- This is the part of the string that doesn't match the pattern
    AddString(subString)

    if not matchStart then
        break -- All matches taken care of
    end
    
    curIndex = matchEnd+1 -- Move the main index to be right after the pattern
    
    AddImage(":BB-5:")
end

This code should work for whatever pattern, so you don’t need to hardcode it for only :BB-5:

Yes, but I need multiple of these in one code block.

Sorry, why can’t you use string.find()? What does multiple of these in one code block mean?

Your code only works for one string. How am I going to use that to, y’know, make multiple emojis that can appear in one message?

You can always use Concatenation. For example, you could loop through all of your strings and concatenate them together.

local function FindPattern(stringToFind:string, pattern:string)
	local curIndex = 1
	local result = ""
	while curIndex <= #stringToFind do
		local matchStart, matchEnd = string.find(stringToFind, pattern, curIndex)
		if not matchStart then
			break -- All matches taken care of
		end
		
		local subString = string.sub(stringToFind, curIndex,matchStart-1) -- This is the part of the string that doesn't match the pattern
		local imageString = string.sub(stringToFind, matchStart, matchEnd)
		local image = GetImage(imageString) -- How are you getting the image?
		result = result..subString..image -- This assumes the image is somehow a "string"

		curIndex = matchEnd+1 -- Move the main index to be right after the pattern
	end
	
	return result
end

So this would work for multiple emojis in the same message. How are you getting the images from the string though? That would require a different way to insert them, not Concatenation.
Thanks to @hannes213 for the original code.

That’s exactly what I was talking about

You can set the pattern to “:.+:” instead and it’ll capture all discord type patterns.

Then, instead of

You could do

AddImage(string.sub(str, matchStart, matchEnd))

And that’s it.

Also

The code above has a bug which I fixed in my response, so use the code in my previous response.
The bug being, the last part of the string wont be concatenated because matchStart would be nil and it’d terminate early, before concatenating the last part of the string

First, the pattern :.-: would be more correct, but %b:: should be equivalent and faster (although that’s unfortunately not an option with my solution).

Next, this really does depend on how you are inserting emojis into the text. If it’s just by inserting normal unicode emojis in, then that’s not a problem, but if you need to create a new ImageLabel instance and insert it at the right position, that increases the complexity a lot. I’m going to assume the first since it should be able to be relatively-trivially extended for the second option.

Using string.gsub would be perfect here if it’s just normal emojis. Your table should instead be a string->string look-up table for this.

local input_string = "this is a test :star:"
local emojis = { star = "⭐" }

-- This pattern captures the shortest string between colons,
--  but uses the text between for the substitution lookup instead of the whole match
local output = string.gsub(input_string, ":(.-):", emojis)

print(output) --> this is a test ⭐

If you’re inserting ImageLabels for each emoji, this becomes a bit more complicated. I originally wrote to try to use string.gsub here, but it’s a lot cleaner if you just loop string.match until there’s no more matches.

-- This pattern will return the text position before the first colon, the contained text, and the position of the last colon
local pos, match, last_match = string.match(input_string, "():(.-):()")
while pos do
	-- last_match + 1 because input_string[last_match] == ":"
	last_match += 1
	local emoji = emojis[match]
	if emoji then
		local before_text = string.sub(input_string, 1, pos)
		-- Some function to find the line of the given string.
		--   Need this because we can't find the correct X position without it.
		local line_text:string, line_y:number = get_line(before_text)
		local line_x:number = TextService:GetTextSize(line_text, fontSize, font, frameSize).X

		-- Create the emoji and place it at the proper position
		local image:ImageLabel = create_emoji(emoji)
		image.Position = UDim2.new(line_x, line_y)

		-- Concat the previous string with an empty space for the emoji + the rest of the string
		input_string = before_text .. "  " .. string.sub(input_string, last_match)
	end
	pos, match, last_match = string.match(input_string, "():(.-):()", last_match)
end

This is the gist of the algo. Finding out the line is honestly a mystery to me, all I can think of is at best using a binary search with TextService.GetTextSize to find the character at which adding the next character would increase the Y value (i.e., aim to keep Y value equal to Y of 1 line), and then repeat that process until you reach the end of the string (summing the amount of lines you’ve passed as well as keeping a reference to the current line).

This might be a really naive approach, and I hope someone more knowledgeable can give a better answer, but I genuinely don’t know if Roblox has the ability to find the position in a TextLabel like that otherwise.

So you’re trying to make a script that replaces things like :BB-5: with emoji’s, and I’m just guessing chat here because why not.

local emojis = {
	[":kaboom:"] = "💥";
	[":mewing:"] = "🗿";
}

function formatStringWithEmojis(string : string,emojiList : {}) : (string)
	--# Explode the string into a table.
	local s = string.split(string," ")
	--# Formats our Table
	for stringPosition,stringSegment in pairs(s) do
		for emojiRequirement,emoji in pairs(emojiList) do
			if string.lower(stringSegment) == emojiRequirement then
				s[stringPosition] = emoji --# This replaces the segment (like :kaboom:) with the 💥 emoji.
			end
		end
	end
	--# Combine the table back in to a string.
	local combinedString = ""
	for _,stringSegment in pairs(s) do
		combinedString = combinedString.." "..stringSegment
	end
	--# Return it.
	return combinedString
end

warn(formatStringWithEmojis("I am about to explode! :kaboom: :mewing:",emojis))

EDIT: I didn’t even know gsub existed all this time lmfao that works too unless you like being able to modify it’s behavior.

Locking this post because I just got nearly banned for my chat script