Is it possible to do string.gsub without the replacement? Does that make sense

So for this thing im making I want to make sure that in the event an incorrectly formatted string is passed, then it is formatted to prevent emergency.

So like, if something in the script ends up being like, 1,2,3,4,Title Here and not 1,2,3,4,"Title Here", it will correct it by placing back in those parentheses.

My current method with gsub kinda works? Its just that the reformatted title ends up missing the first and last letters because they get replaced with the quotations, would it be possible to just squeeze in a quotation between the comma and a letter if there is one? Does this make sense?

Try this:

local inputString = "1,2,3,4,Title Here"
local correctedString = string.gsub(inputString, "(%d+,%d+,%d+,%d+),([%w%s]+)", "%1,\"%2\"")

print(correctedString) -- 1,2,3,4,"Title Here"

Here’s how the gsub pattern works:

  • (%d+,%d+,%d+,%d+): This pattern matches four groups of digits separated by commas. This assumes your initial part of the string contains exactly four comma-separated numbers.
  • ,([%w%s]+): This pattern captures the title part, which can consist of alphanumeric characters (%w) and spaces (%s).
1 Like

Thank you very much! I do have one question though, so the pattern right now just assumes that the string is just 4 comma-separated numbers right? Would there be anyway to make it work in cases of there being more numbers or?

Just write a parser, that validates the format you are requiring. It will probably be faster to do that then to play around with regex type formatting and using g sub, in my opinion.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.