Lua:如何检查字符串是否只包含数字和字母



简单的问题可能有一个简单的答案,但我目前的解决方案似乎很糟糕。

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

有更好的方法吗。。也许是用string.sub?

提前谢谢。

如果您想查看字符串是否只包含字母数字字符,请将该字符串与所有非字母数字字符进行匹配:

if(str:match("%W")) then
  --Improper characters detected.
end

模式%w与字母数字字符匹配。按照惯例,模式than是大写而不是小写,匹配相反的字符集。因此%W匹配所有非字母数字字符。

您可以使用[] 创建集合匹配

local patt = "[?!@]"
if string.match ( mystr , patt ) then
    ....
end

请注意,lua中的字符类只适用于单个字符(而不是单词)。有内置类,%W匹配非字母数字,所以继续使用它作为快捷方式。

您还可以将内置类添加到您的集合中:

local patt = "[%Wxyz]"

将匹配所有非字母数字AND字符xyz

我使用这个Lua二行:

  local function envIsAlphaNum(sIn)
    return (string.match(sIn,"[^%w]") == nil) end

当它检测到非字母数字时,它会返回错误的

最新更新