Reputation: 1128
Simple question may have a simple answer, but my current solution seems horrible.
local list = {'?', '!', '@', ... etc)
for i=1, #list do
if string.match(string, strf("%%%s+", list[i])) then
-- string contains characters that are not alphanumeric.
end
end
Is there a better way to do this.. maybe with string.gsub?
Thanks in advance.
Upvotes: 6
Views: 24381
Reputation: 902
I use this Lua two-liner:
local function envIsAlphaNum(sIn)
return (string.match(sIn,"[^%w]") == nil) end
When it detects a non-alphanumeric it returns false
Upvotes: 1
Reputation: 473272
If you're looking to see if a string contains only alphanumeric characters, then just match the string against all non-alphanumeric characters:
if(str:match("%W")) then
--Improper characters detected.
end
The pattern %w
matches alphanumeric characters. By convention, a pattern than is upper-case rather than lowercase matches the inverse set of characters. So %W
matches all non-alphanumeric characters.
Upvotes: 12
Reputation: 4311
You can create a set match with []
local patt = "[?!@]"
if string.match ( mystr , patt ) then
....
end
Note that character classes in lua only work for single characters (not words).
There are built in classes, %W
matches non-alphanumerics, so go ahead and use that as a shortcut.
You can also add the inbuilt classes to your set:
local patt = "[%Wxyz]"
Will match all non-alphanumerics AND characters x
, y
or z
Upvotes: 5