【问题标题】:Lua: How to check if a string contains only numbers and letters?Lua:如何检查字符串是否只包含数字和字母?
【发布时间】:2012-08-20 12:33:49
【问题描述】:

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

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.gsub?

提前致谢。

【问题讨论】:

  • 什么是“strf”? $list 是什么?这不是一个有效的 Lua 操作符。
  • 我创建的东西,它是 string.format 的简写。
  • 打字有点太快了,没有回头,它是固定的:P

标签: lua pattern-matching alphanumeric non-alphanumeric


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您可以使用[]创建一组匹配

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

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

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

    local patt = "[%Wxyz]"
    

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

    【讨论】:

      【解决方案3】:

      我使用这个 Lua 两线:

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

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

      【讨论】:

        猜你喜欢
        • 2011-07-11
        • 1970-01-01
        • 2017-11-02
        • 1970-01-01
        • 2021-10-01
        • 2013-03-08
        • 1970-01-01
        • 2020-12-12
        • 2015-01-04
        相关资源
        最近更新 更多