How to check if a string contains only certain characters?

How do I create a function that checks if a string only contains certain characters and if it contains any other characters it returns false? For example, let the letters be {“a”, “b”, “c”, d"}. “dbc” should return true and “cbaw” should return false, because “dbc” consists of only characters in the list, while “cbaw” contains a foreign character, “w”.

Try iterating through the word and table.find each character to your table of valid chars. Something like:

local chars = {"a","b","c","d"}

local word = "cbaw"

for char in word:gmatch(".") do
	print(string.format("character '%s' is %s.", char, table.find(chars, char) and "valid" or "not valid"))
end

--[[
Output:
 character 'c' is valid.
  character 'b' is valid.
  character 'a' is valid.
  character 'w' is not valid.
]]

This will just print if it exists in the table or not, you can adapt the logic to printing if the whole word is valid or not though.

I think this should work. At least for the example you provided.

local validPatt = "^[abcd]+$" --Should match any combo of the characters in the set and only those.
local testString = "cbaw"
if(string.match(testString, validPatt))then
	print("String Ok!")
else
	print("String Invalid!")
end

As a function:

local function StringValid(str: String, patt: String)
	if(string.match(str, patt))then
		return true
	end
	
	return false
end
local whitelistedChars = {"a", "b", "c", "d"}

local function isStringWhitelisted(strings)
	for char in strings:gmatch(".") do
		if not table.find(whitelistedChars, char) then
			return false
		end
	end
	return true
end

print(isStringWhitelisted("dbca")) --true
print(isStringWhitelisted("zxy")) --false
local function isStringWhitelisted(strings)
	for char in strings:gmatch(".") do
		if char:byte() < 97 or char:byte() > 100 then
			return false
		end
	end
	return true
end

print(isStringWhitelisted("dbca")) --true
print(isStringWhitelisted("zxy")) --false
1 Like