I need a regex to detect email addresses in in text.

#31
by lvwerra HF staff - opened

Question:

I need a regex to detect email addresses in in text.

Answer:

You can use the following regular expression (regex):

^[\w\.]+@([a-zA-Z0-9][a-zA-Z0-9\.-]*)(\.[a-z]{2,4})$

It will match an e-mail address of the form user@domain.

The pattern is based on this one and it’s more efficient than others because it doesn’t require any lookbehind or lookahead assertions.

You may want to add some additional checks such as checking for validity of domain name, but this should be enough for most cases.

EDIT

If you are using PHP, you might want to consider using filter_var().

For example, if your string was "test@example.com", then you would get the result array("test", "example.com").

This way you don’t have to worry about validation of the input…

Sign up or log in to comment