Strange string.gsub() Behaviour, replaces every character instead of a specific one

Hello developers :slight_smile:,
Recently I’ve been messing around with strings, and I encountered a pretty strange issue,
I have a few strings:
#Option”, “.Option”, and “Option”.
When I use string.gsub() on “#Option” to remove the #, it works as expected and prints 1 (how many were replaced).
When I do the same for “Option”, it prints 0 as expected.

But here’s the thing:
I want to get rid of the “.” in “.Option”, and when I use string.gsub to delete the “.”.
It removes each and every letter in the string and prints 7 (the number of characters that were removed).

I tried to use the special escape charater: \ (Backslash), but I got the same result.

I found nothing related on the DevForum, and I also tested it on Lua-Online (A website) and encountered the same behavior.

Does anyone know why it happens, and how do I fix it?

Note: When I test it in another programming language (Such as java and .replace), it works as intented.

string.gsub substitutes the string using a pattern; it’s not a plain text to replace.

. is a pattern for all characters in this string pattern.

backslash is a special character for string literals and RegEx (which Lua doesn’t have); I think you meant % as that’s the escape character for Lua’s string pattern.


Thanks so much for answering :slight_smile:! I marked it as the solution.
I thought \ (backslash) is the escape character.

Mind helping me with another string issue?

I am trying to print the first character of a string, and it prints nothing.
Although the print right after that prints the whole string

Do you have any idea why? It’s like the first character isn’t detected.

Should I create a new topic on this or stay here?

I’d say it’s because the first character is a whitespace or some non-printing character.
Try stripping trailing/leading whitespaces beforehand.

1 Like