Regular Expression to extract strings between angle brackets with exactly one @ char in between

Viewed 65

Does any one have an idea how to match something like

<t@t.com>

I tried this regular expression

\<(.?*)\>

but this matches also <sddsds> I want it to match where inside <> is an email with @ sign.

2 Answers

You can use

<([^<>@]+@[^<>@]+)>

See the regex demo. Details:

  • < - a < char
  • ([^<>@]+@[^<>@]+) - Group 1: any one or more chars other than <, > and @, a @ char and then again any one or more chars other than <, > and @
  • > - a > char.

See the PHP demo:

$str = "<t@t.com>\n<tatacom>\n<t@ata@com>";
$re = '/<([^<>@]+@[^<>@]+)>/';
if (preg_match_all($re, $str, $matches)) {
    print_r($matches[1]);
}
// => Array( [0] => t@t.com )

You can use this:

$regex = '/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/'

Related