Javascript Regular Expression - Limit number of valid characters

I'm learning regular expressions in javascript and I think there is something I'm missing.

I'm using an example where I'm trying to extract valid email addresses from a string. I'm getting the valid emails but I'm also getting invalid ones. Here's the code:

var teststring = "This is my test string with a valid email: this@that.com,
             and an invalid email: this@broken.1. Pull only the valid email.";

teststring.match(/[A-Za-z0-9_+.-]+@[A-Za-z0-9]+.[A-Za-z]{2,3}/g)

When I run the match method, I get both the valid email "this@that.com" and the invalid email "this@broken.1" returned.

I thought the {2,3} at the end of the last square brackets was supposed to specify that the particular character search within the brackets should only be valid if they contain 2 to 3 instances of the criteria, so why does the broken email with just the "1" after the last dot get returned?

I should also add that I totally understand that this is not a be all end all email validation expression. This is purely a trying-to-understand-regular-expressions question for me. I was searching around for a clear answer but couldn't find exactly what I was looking for.

Thanks

Answers


You need to escape that last .. Otherwise, it means "match any character", so the expression is catching these chunks:

this
@
brok
en

try:

teststring.match(/[A-Za-z0-9_+.-]+@[A-Za-z0-9]+\.[A-Za-z]{2,3}/g)

. will match any character. To match an actual . you need \.

teststring.match(/[A-Za-z0-9_+.-]+@[A-Za-z0-9]+\.[A-Za-z]{2,3}/g)

Need Your Help

Centered Top Navigation Menu with 2 Elements

html css

Hi i'm encountering an absolute stupid problem. iam currently designing a website with an center which includes two elements, a logo and an navigation icon. Between these two things should be a space

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.