Need some help with string.match

I am trying to use the tag names used in CollectionService to set some variables and I am having a hard time using string.match to do this.

each instance is tagged with three tags like so:
“Spawner”
“Type_1”
“Region_1A”

I want to be able to set some variables based on Type and Region, I wont be using the Spawner tag in this operation.

here is the code I am trying to use:

for a,b in pairs(CollectionService:GetTagged("Spawner")) do
	-- apply basic settings
	b.Transparency = 1
	local position = b.Position

	-- get all the tags and set the variables
	local Tags = CollectionService:GetTags(b)
	local SpawnerType
	local Region
	local pattern = "() _ ()"
	for c,d in pairs (Tags) do
		if d ~= "Spawner" then
            print(c,d) -- this will print correctly
			local key, val = string.match(d,pattern)
			print(key,val) -- this is printing nil,nil
		end
	end
end

As you can see in the sample above, there are two print statements. I have added some comments. The first print does print the key and value properly for c and d. The second print statement prints nil,nil.

I am not sure why, i suspect it has something to do with the pattern i am using but bit sure.

What i want to be able to split a tag name such as “Region_1A” into: key = “Region” and value = “1A”

Thanks in advance!

I’m lazy and forgot how string patterns work, so I just use string.split instead for something this simple.

local FULL_STRING = "Spawner_1A" -- Comes from GetTags or whatever
local stringPieces = string.split(FULL_STRING, "_") --> {"Spawner", "1A"}
local key = stringPieces[1] --> Spawner
local value = stringPieces[2] --> 1A

That being said, I think the proper string pattern is “(*.)_(*.)” if you’re trying to use string.match.

1 Like

Thanks, didn’t find string.spit on the wiki :slight_smile:

I assume this was just a typo, but you put the asterisk and period in the wrong order; a period is any character and an asterisk specifies 0 or more of the preceding character. It’s not a big issue since string.split definitely works fine in this case.

To main post: In terms of future projects, if for some reason you’d only want to match to just the first underscore (e.g “test” and “1” in "test_1_2") it might be better to do "([^_]*)_([^_]*)" as your pattern, as this would be any number of non-underscore characters, an underscore, and then any number of non-underscore characters.

1 Like