Javascript 正则表达式 - 必须以字母开头只能出现一次特殊字符

Javascript Regex - must starts with letters can only have one occurrence of special character

我是正则表达式的新手,正在尝试根据以下特定要求创建一个正则表达式:

  1. 必须以字母 a-Z 或 A-Z 开头
  2. 可以包含数字 0-9
  3. 只能包含允许的特殊字符,即 @.-'
  4. 以上特殊字符只允许出现一次,即 test9@my.com 或 new-test10@me.com 有效,但 test5@new@com 无效

我尝试了以下代码但无法满足所有要求 -

var myregex = /^([a-zA-Z0-9@.\-'])*$/;
if(!myregex.test(userIdVal)){
    alert('invalid');
}

感谢任何帮助。

我建议在检查 @.-' 字符是否只使用一次时取消正则表达式:

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");
}

我认为这行得通,只需将特价夹在其他菜品之间即可。

^(?=[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
 $

试试这个:var myregex = /^[a-zA-Z]+[a-zA-Z\d]*[@\.-][a-zA-Z\d]*$/
它可能看起来不够整洁,但是嘿,这是一个正则表达式 :>