How to make sure a string only contains letters and numbers

Hi!. Is there anyway to make sure that a string contains letters and numbers?

I know that Character modifiers/Patterns exist but from the documentary i cant find how to solve my issue.

I have tried to write a list of special characters (",#,$,% etc) in a table and loop into them, then use string.find() to check if any of the characters in the table are in the string but i just noticed that players can Copy and paste characters like ( ÷,❆ and more).

Does anyone have an idea on how i can archive this? (Make sure a string only contain letters and numbers)

local s = "hello world"

if (string.match(s, "[%w%s]+") == s) then
	print("'s' contains only letters, numbers, and spaces.")
else
	print("'s' contains a special character.")
end

Without spaces:

if (string.match(s, "%w+") == s) then
	print("'s' contains only letters and numbers")
else
	print("'s' contains a special character.")
end
1 Like

Worked like a charm!
Thanks ALOT!

You can use string.match with string patterns.

To get only letters and numbers, use the pattern [%w]+. This returns the string with any letter or number.

Example:

local String = "Hello, w❆orld."

local FilteredString = String:match("[%w]+")

print(FilteredString) -- Expected output: "Hello,world."

You can also change it to contain spaces or other things. Read more about string patterns below, and string.match below:

String Patterns, 1
String Patterns, 2
string.match and other functions of string.

2 Likes

What do I do if I want o remove any letter that isn’t formatted as “[%w%s%p]+”? using string.gsub().