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?
-
4TLDs are not limited to having 2-4 letters in them…Quentin– Quentin2011-07-04 10:00:29 +00:00Commented Jul 4, 2011 at 10:00
-
3For that matter, they aren't limited to latin script eitherQuentin– Quentin2011-07-04 10:02:13 +00:00Commented Jul 4, 2011 at 10:02
-
1Can you show us your actual code that's not working, not just the regex? (BTW, using a regex to validate an email address is generally considered a bad idea, since it's actually impossible)Jonathan Hall– Jonathan Hall2011-07-04 10:03:17 +00:00Commented Jul 4, 2011 at 10:03
-
1@Flimzy - agreed. I just check for the existence of the "@" as a basic sanity check: stackoverflow.com/questions/6533344/…Richard H– Richard H2011-07-04 10:04:33 +00:00Commented Jul 4, 2011 at 10:04
-
1I'm not sure about the first 'b'? Do you really want just email addresses starting with a 'b'?flori– flori2011-07-04 10:04:59 +00:00Commented Jul 4, 2011 at 10:04
2 Answers
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)
2 Comments
\b at the end. I think the OP made a misunderstanding when adding delimiters.\b at either end. Excellent article.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