代码之家  ›  专栏  ›  技术社区  ›  unwise guy

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

  •  4
  • unwise guy  · 技术社区  · 13 年前

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

    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?

    提前谢谢。

    3 回复  |  直到 13 年前
        1
  •  10
  •   Nicol Bolas    9 年前

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

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

    图案 %w 匹配字母数字字符。按照惯例,一个比是大写而不是小写的模式匹配相反的字符集。所以 %W 匹配所有非字母数字字符。

        2
  •  4
  •   daurnimator    13 年前

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

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

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

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

    local patt = "[%Wxyz]"
    

    将匹配所有非字母数字和字符 x , y z

        3
  •  0
  •   Деян Добромиров    9 年前

    我用的是Lua二衬:

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

    当检测到非字母数字时,返回false