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

unw*_*guy 1 lua alphanumeric non-alphanumeric pattern-matching

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

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
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来做到这一点..也许与string.gsub?

提前致谢.

Nic*_*las 7

如果您要查看字符串是否仅包含字母数字字符,那么只需将字符串与所有非字母数字字符匹配:

if(str:match("%W")) then
  --Improper characters detected.
end
Run Code Online (Sandbox Code Playgroud)

该模式%w匹配字母数字字符.按照惯例,大于而不是小写的模式匹配反向字符集.因此%W匹配所有非字母数字字符.


dau*_*tor 5

您可以创建一组匹配[]

local patt = "[?!@]"

if string.match ( mystr , patt ) then
    ....
end
Run Code Online (Sandbox Code Playgroud)

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

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

local patt = "[%Wxyz]"
Run Code Online (Sandbox Code Playgroud)

将匹配所有非字母数字 AND 字符xy或者z