Write a regular expression which matches a email address

Answer: This is very tricky question. Matching emails is not as trivial as it seems and the answer can be as simple as

\w+@\w+\.[\w]{3}

or as messy as

^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}

Remember, it is interview question, not production code. So, be simple. I always recommend starting with basics:

\w+@\w+\.[\w]{3}

Then explain its limitations and give couple examples there the pattern would give false positive or false negative results. (such as test@test.111). From my experience, usually it is more than enough to impress interviewer. From the other side, you always can iteratively enhance this pattern engaging interviewer into the conversation giving you the chance to showcase your knowledge.

Another popular question is also about parsing HTML







Answers and Comments