我在 PHP 中使用以下代码来验证密码是否包含无效字符
function validate_password($str) {
if(strlen($str) < 5 || strlen($str) > 30) {
return false;
} else {
return preg_match('/^[-._A-Za-z0-9]*$/',$str);
}
}
我正在尝试在 Lua 中执行相同的操作,但不确定检查字符串是否仅包含某些字符的最佳方法。我的有效字符是字母数字加上“-”和“.”
local function validate_password(str)
if string.len(str) < 5 or string.len(str) > 30 then
return false
else
if(str:match("%W")) then
-- this isn't right. need to check if alpha numeric or - or .
return false
else
return true
end
end
end
感谢任何帮助!
最佳答案
return #str >= 5 and #str <= 30 and str:find('^[%-%.%w_]+$') ~= nil
注1:如评论中所述,~= nil
部分可以被删除,因为 find
返回的位置将被评估为 true
(当它不为零时)在逻辑运算符中。但是,由于它是一个数字,因此在 validate_password(str) == true
中使用时会失败。比较(因为 1 == true
不是 true
)。另一种方法是使用 not str:find('[^...]')
正如叶戈尔的建议。
注2:正如评论中提到的,-
和.
在这种特殊情况下不需要转义。然而,自从 -
是方括号内的范围运算符 [_-.]
与[-._]
不相同,因为它不会匹配 _
之间的符号范围。和.
是空的。逃生安全了-
和.
即使在方括号内。
关于string - Lua - 检测字符串是否包含密码的有效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16822807/