开发者

How do you match a regex in javascript?

I'm trying to match the email regex \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b with a string in Javascript. At the moment I'm using the code email.match(/b[A-Z0-9开发者_运维技巧._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/) but it doesn't match any email addresses. Do regex's need to be changed before they are used in Javascript?


Problems matching email addresses with regex aside:

You have to add the case-insensitive modifier since you are only matching uppercase characters. You also are missing the \ in front of the b (which makes the expression match a b literally) and the \b at the end (thanks @Tomalak) (even though it will "work" without it):

email.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)

If you only want to know whether the expressions matches or not, you can use .test:

patter.test(email)

More about regular expressions in JavaScript.


You should use a RFC 2822 compliant RegEx for validating emails, even if it's a big one;

function check_mail(str){
    var reg=new RegExp(/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i)

  if(str.match(reg)){
    return true;
  }else{
    return false;
  }
}

For more details on validating email using RegExs see regular-expression.info

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜