javascript 正则表达式严格检查字母数字和特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18863477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regex to strictly check alphanumeric and special character
提问by Ravi
To check alphanumeric with special characters
检查带有特殊字符的字母数字
var regex = /^[a-zA-Z0-9_$@.]{8,15}$/;
return regex.test(pass);
But, above regex returns true
even I pass following combination
但是,true
即使我通过以下组合,上面的正则表达式也会返回
asghlkyudet
asghlkyudet
78346709tr
78346709tr
jkdg7683786
jkdg7683786
But, I want that, it must have alphanumeric and special character otherwise it must return false for any case. Ex:
但是,我希望它必须具有字母数字和特殊字符,否则在任何情况下它都必须返回 false。前任:
fg56_fg$
fg56_fg$
Sghdfi@90
Sghdfi@90
回答by nhahtdh
Use look-ahead to check that the string has at least one alphanumeric character and at least one special character:
使用先行检查字符串是否至少包含一个字母数字字符和至少一个特殊字符:
/^(?=.*[a-zA-Z0-9])(?=.*[_$@.])[a-zA-Z0-9_$@.]{8,15}$/
By the way, the set of special characters is too small. Even consider the set of ASCII characters, this is not even all the special characters.
顺便说一下,特殊字符集太小了。即使考虑 ASCII 字符集,这甚至不是所有特殊字符。
回答by Bohemian
You can replace a-zA-Z0-9_
with \w
, and using two anchored look-aheads - one for a special and one for a non-special, the briefest way to express it is:
您可以替换a-zA-Z0-9_
为\w
, 并使用两个锚定前瞻 - 一个用于特殊的,一个用于非特殊的,最简单的表达方式是:
/^(?=.*[_$@.])(?=.*[^_$@.])[\w$@.]{8,15}$/
回答by Mario.Hydrant
The dollar sign is a reserved character for Regexes. You need to escape it.
美元符号是正则表达式的保留字符。你需要逃避它。
var regex = /^[a-zA-Z0-9_/$@.]{8,15}$/;