Is there way to get string.find to return a table of all found spots?

If you do

print(string.find("hello there. I say hello. hello I say","hello"))

it will return the same thing as

print(string.find("hello there","hello"))

Is there a function that could return a table of the position of all the different "hello"s?

  • What are you attempting to achieve?
    The end goal is colorful syntax highlighting ingame

  • What is the issue?
    string.find only shows the first piece it finds, not all the pieces.

  • Solutions I’ve thought of:
    I could loop through and replace each print temporarily with some strange unused character and then change it all back at the end, but that seems like a lot of work

2 Likes

You could use string.gmatch and store each found value in a table.

1 Like
local function findAll(str, sub)
	local found = 0
	local positions = {}
	while(found)do
		found = found + 1
		found = str:find(sub, found)
		table.insert(positions, found)
	end
	return positions
end

string.find has another parameter that will look for the substring you provide it starting at that position
ex: string.find(str, sub, 2) will never find the substring if it starts at position 1

10 Likes

If your goal is in-game syntax highlighting, I would suggest taking a look at this:

https://devforum.roblox.com/t/lexer-for-rbx-lua/183115

1 Like

Awesome!
Thanks.
This module will save me lots of time

2 Likes