要求:
正则表达式应匹配一个不包含“ @”符号,但至少包含两个字母字符,且总长度为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}$
最佳答案
您的正则表达式不会检查至少两个Alpha。
您可以使用以下正则表达式:
^(?=(?:[^A-Za-z]*[A-Za-z]){2})[^@]{2,50}$
请参见regex demo
说明:
^
-字符串开始(?=(?:[^A-Za-z]*[A-Za-z]){2})
-必须至少出现两次零个或多个非字母字符,后跟一个字母[^@]{2,50}
-@
以外的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/>";
}
关于javascript - JavaScript正则表达式-匹配一个包含一些字符但不包含其他字符的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35349947/