Multi-line string.gsub() troubles

Hello :wave:, I am having problems with string.gsub() and can’t figure out the correct patterns to be working with. :thinking:

Description is the following string:

Type: Training Session
Host: Nicklaus_s
Co-Host: TypicallyShadow
string.gsub(Description, ':(.*):(%a*):(%a*)', function(Type, Host, CoHost)
    print(Type, Host, CoHost)

I am attempting to isolate Training Session, Nicklaus_s, and TypicallyShadow. So Type would be equal to Training Session, Host would be equal to Nicklaus_s, and CoHost would be equal to TypicallyShadow.

Please help as soon as possible. :smile:

1 Like

string.gsub is not RBXScriptConnection
This is how you do it

print(string.gsub('hello world', 'world', ''))

Prints ‘hello world’ without the word ‘world’

1 Like

But this might help:

local Description = {
	['Type'] = 'Training Session',
	['Host'] = 'Nicklaus_s',
	['Co-Host'] = 'TypicallyShadow'
print(Description.Type, Description.Host, Description["Co-Host"])
1 Like

Yes, of course. However, string.gsub does infact take a function as a third parameter. Infact, this was in docs:

-- Replacement function
string.gsub("I have 2 cats.", "%d+", function(n)
       return tonumber(n) * 12 
end) --> I have 24 cats.

It seems the function returns something to use as the 3rd parameter in the gsub function. If you want to print the result, try print(string.gsub(...))

1 Like

I understand how string.gsub() works, I just am unable to figure out the correct patterns to use. The enters (whitespace) in my Description is the ultimate problem.

1 Like

I’m not familiar with gsub, but perhaps you could try this alternative method:

local str = ... -- Your string
local lines = string.split(str, '\n')

local data = {}
for _,line in pairs(lines) do
    local Type,value = string.split(line, ": ")
    data[line] = value
... -- Do whatever with data

I haven’t tested it, and I wrote in the devforum. I know this is much longer than it needs to be, but it’s just an alternative way. Data should be something MicrosoftWindowsRBX said.

1 Like

I came up with this in a few minutes.

local data = {}
local str = [[Type: Training Session
Host: Nicklaus_s
Co-Host: TypicallyShadow]]

for i in str:gmatch("[^\n]+") do
    local v1, v2 = i:match("(.+): (.+)")
    data[v1] = v2

for i, v in pairs(data) do
    print(i, "\t", v)

Type	Training Session
Host	Nicklaus_s
Co-Host	TypicallyShadow

Basically gmatch will capture anything in a set that’s not a newline (\n) and return it. Then using match will capture before and after the colon (:). I hope this helps :+1: