Help with string manipulation

Hello.

I’m trying to store the values after the colons in variables, but I just can’t figure out how to do it properly without conflicting with the words before the colons.

This is the plain string that I’m trying to filter out:

Code: 2371
Title: Important notice
Body: This is epic
ImageId: 0
Button: Dismiss
ShowTo: {149875749, 149875749, 149875749}
Expiration: never

I’m trying to get the values (2371, Important notice, Dismiss, etc.) after the colons and storing them into variables, but how can I do that?

local exampleValue = yourString:match("Code: (.-)\n") 

‘Code’ can be ‘%a+’ or other values

3 Likes

You can try out this quick parser I made:

local text = [[
Code: 2371
Title: Important notice
Body: This is epic
ImageId: 0
Button: Dismiss
ShowTo: {149875749, 149875749, 149875749}
Expiration: never
]]

local data = {}

local function cutOffWhitespaceFromEnds(str)
	local a = str:find("%S")
	local b = str:reverse():find("%S")
	if (a and b) then
		return str:sub(a, #str - b + 1)
	end
end

local function processData(str)
	str = cutOffWhitespaceFromEnds(str)
	if (str == nil) then
		return nil
	elseif (tonumber(str) ~= nil) then -- number
		return tonumber(str)
	elseif (str:sub(1, 1) == "{" and str:sub(-1) == "}") then -- array
		local stuff = str:sub(2, -2):split(",")
		local things = {}
		for _, v in ipairs(stuff) do
			table.insert(things, processData(v))
		end
		return things
	else -- otherwise assume it's a plain string
		return str
	end
end

-- first separate the lines of the text
local lines = text:split("\n")
for i, v in ipairs(lines) do
	-- self explanatory 
	local line = cutOffWhitespaceFromEnds(v)
	if (line ~= nil) then
		-- look for a colon then separate the text on either side
		local colon = line:find(":", 1, true)
		if (colon ~= nil) then
			-- pack into the result table
			local key = line:sub(1, colon - 1)
			local remainder = line:sub(colon + 1)
			data[key] = processData(remainder)
		end
	end
end

--test
for i, v in pairs(data) do
	print(i, "\t", v, "\t", typeof(v))
end
print("---")
for _, v in ipairs(data.ShowTo) do
	print(v, "\t", typeof(v))
end

Output:

  Expiration 	 never 						 string
  Title 		 Important notice 			 string
  Code 			 2371 						 number
  Button 		 Dismiss 					 string
  ShowTo 		 table: 0x1b4b530820373419 	 table
  ImageId 		 0 							 number
  Body 			 This is epic 				 string
  --- (contents of data.ShowTo)
  149875749 	 number (x3)
2 Likes

Thanks so much! Your one-line code saved me from ripping my hair out trying to figure this out lol.

Also thanks @Blokav for the help. I didn’t get to try out your parser, but thanks for taking time and effort into writing it!