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

时间:2017-07-27 20:15:55

标签: javascript regex find-occurrences

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

  1. 必须以字母a-Z或A-Z
  2. 开头
  3. 可以包含数字0-9
  4. 只能包含允许的特殊字符,即@ .-'
  5. 只允许出现一次以上特殊字符,即test9@my.com或new-test10@me.com有效,但test5 @ new @ com无效
  6. 我尝试过以下代码,但无法满足所有要求 -

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

    感谢任何帮助。

3 个答案:

答案 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;