要求:
正则表达式应该匹配一个不包含“@”符号的字符串,但至少包含两个字母字符,总长度在2到50个字符之间。
通过示例:
"Hi there!%%#"
" fd"
" 9 z 80212132 z"
失败示例:
"anything with @"
"a"
" 9 z 80212132 "
"This string does not contain at symbol and has two characters but is too long!"
我相信我很接近,但是除了[a-zA-Z]之外的任何角色都会失败,我不知道为什么:
^((?![@])(?=[a-zA-Z]).){2,50}$
答案 0 :(得分:2)
你的正则表达式不检查至少两个alpha。
您可以使用以下正则表达式:
^(?=(?:[^A-Za-z]*[A-Za-z]){2})[^@]{2,50}$
请参阅regex demo
解释:
^
- 字符串开头(?=(?:[^A-Za-z]*[A-Za-z]){2})
- 必须至少出现两次零个或多个非字母字符后跟一个字母[^@]{2,50}
- 除@
$
- 字符串结束。
var re = /^(?=(?:[^A-Za-z]*[A-Za-z]){2})[^@]{2,50}$/;
var strs = ['Hi there!%%#', ' fd' , ' 9 z 80212132 z', 'anything with @ a', ' 9 z 80212132 ', 'This string does not contain at symbol and has two characters but is too long!'];
// demo
for (var s of strs) {
document.body.innerHTML += "<i>" + s.replace(/ /g, ' ') + "</i> test result: <b>" + re.test(s) + "</b><br/>";
}
&#13;
答案 1 :(得分:0)