2 regular expressions in 1

4

I found the following regular expression to validate email address in javascript:

/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

That works very well. I would like to add, in this same expression, the minimum and maximum character limitations:

/^.{3,100}$/

One less elegant solution is to do 2 checks (which is what I'm doing today). Is it possible to leave everything in a single expression?

    
asked by anonymous 22.07.2014 / 15:00

1 answer

5

Yes, you can use lookarounds :

(?=regex1)regex2
(?!regex1)regex2

In the first case ( positive lookahead ), the engine checks that the string matches the regex1 , but does not actually consume it, and then proceeds to the normal match with regex2 . In the second ( negative lookahead ) it is the same, but the engine checks to see if the string does not matches with regex1 .

Adapting to your case, it would look like this:

(?=^.{3,100}$)^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$

Example in jsFiddle (I used 15-20 characters to simplify the test). Source: this question in SOen .

    
22.07.2014 / 16:01