How would I format strings to string patterns?

Basically what I’m asking is how to place a ‘%’ character in front of every character that is non-alphanumerical and non-whitespace.

e.g.

local str = "Hello! I'm *!(("
local function x(y: string): string
...
end
print(x(str)) --"Hello%! I%'m %*%!%(%("

You can use the string.gsub function with the pattern "[^%w%s]" and the replacement "%%%1".

In the pattern, we used the square brackets to match anything inside them which are not characters that are alphanumeric (%w) or characters that are spaces (%s).
In the replacement, we escaped the percentage magic character by writing it twice and we used it as a magic character combined with “1” to insert the captured character back.

Here is the demo.

local str = "Hello! I'm *!(("
local transformed = string.gsub(str, "[^%w%s]", "%%%1")
print(transformed)  -- output: "Hello%! I%'m %*%!%(%("

I suggest that you read the documentation on string patterns to understand how to use them.

1 Like

Thank you, that was surprisingly less complicated than I expected.
Quick question out of curiosity, could you explain how this works?

EDIT: Ooh ok thanks I understand now.

1 Like

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