Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: How to check if a string contains only numbers and letters?

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.

like image 253
unwise guy Avatar asked Dec 08 '22 21:12

unwise guy


1 Answers

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.

like image 160
Nicol Bolas Avatar answered Jan 07 '23 19:01

Nicol Bolas