How to split a string by one of several characters

My question is, how does one split a string by one of two characters, here is my current code:

CurrentTextTracker = CurrentTextLabel.Code:GetPropertyChangedSignal('Text'):Connect(function()
	local Text = CurrentTextLabel.Code.Text
	local TableOfWords = string.split("Text", " ")
end)

And my aim is to split the text whenever a whitespace or a comma is found

There is a function in Roblox called string.split that returns the table.

local str = "Hey,There,Person"
local strTable = str:split(",")
for _,str in pairs(strTable) do
   print(str)
end

I hope I helped you! :slight_smile:

May I just ask how this solves my issue?

It’s just an example I gave. You can add a function string.split and add a character that can split the text, making it so the script splits the text when there is a whitespace or a comma.

I think you will have to use string.gsub which accepts string patterns.

Ive identified I know what string.split Is in my post

I really don’t understand what you are asking for, may you explain please?

Yes, it is not possible to use string.split with multiple separators. That is why I suggested using string.gsub which accepts a string pattern and you can make a pattern that divides strings by space/comma.

Text = string.gsub(Text,"[%s%p]+", " " )
local TableOfWords = string.split(Text, " ")

This is what I ended up using, works by converting whitespace / punctuation to whitespace then splits it by whitespace, an annoying workaround but it works fine.

Credit to @COUNTYL1MITS for pointing me towards gsub for this use case.

3 Likes