我是正则表达式的新手,并尝试根据以下具体要求创建一个表达式:
我尝试过以下代码,但无法满足所有要求 -
var myregex = /^([a-zA-Z0-9@.\-'])*$/;
if(!myregex.test(userIdVal)){
alert('invalid');
}
感谢任何帮助。
答案 0 :(得分:1)
我建议在检查@.-'
字符只使用一次时取消正则表达式:
var myregex, specialCharOccurrences, i, key;
// Test to see that only the allowed characters are used
myregex = /^([a-zA-Z0-9@.\-'])*$/;
if(!myregex.test(userIdVal)){
alert('invalid');
// Test for multiple occurrences of the special characters
// a) create object in which the number of occurrences of the special characters are stored
specialCharOccurrences = {
"@": 0,
".": 0,
"-": 0,
"'": 0
};
// b) count the number of occurrences. If the # is greater than 1, send an alert.
for (i = 0; i < userIdVal.length; i++) {
if (/[@.\-']/.test(userIdVal[i])) specialCharOccurrences[userIdVal[i]]++;
if (specialCharOccurrences[userIdVal[i]] > 1) alert("invalid");
}
答案 1 :(得分:1)
我认为这是有效的,只是将其他人之间的特殊内容夹在中间。
^(?=[a-zA-Z])[a-zA-Z0-9]*[@.'-]?[a-zA-Z0-9]*$
解释
^
(?= [a-zA-Z] ) # A char is in this string and starts with
[a-zA-Z0-9]* # Optional alnums
[@.'-]? # Optional single special
[a-zA-Z0-9]* # Optional alnums
$
答案 2 :(得分:0)
试试这个:var myregex = /^[a-zA-Z]+[a-zA-Z\d]*[@\.-][a-zA-Z\d]*$/
它可能看起来不是很整洁但是嘿,这是一个正则表达式:&gt;