0

So I have those examples:

  • "torvalds@linux.org"
  • "Elon <42069@tesla.com>"
  • "Suzzy@Typo.com <suzzy@peppapig.com>"

with one regular expression I would like to be able to extract from them respectively:

  • "torvalds@linux.org"
  • "42069@tesla.com"
  • "suzzy@peppapig.com"

My miserable attempts were able me so far to came up with something like:

/^(?:([^<>]+)|(?:.*<(.*?)>))$/

but with that I'm not able to make a single group capture an email address:

> var emailRegex = /^(?:([^<>]+)|(?:.*<(.*?)>))$/;
undefined
> linus.match(emailRegex)
[
  'torvalds@linux-foundation.org',
  'torvalds@linux-foundation.org',
  undefined,
  index: 0,
  input: 'torvalds@linux-foundation.org',
  groups: undefined
]
> SuzzysEmail.match(emailRegex)
[
  'Suzzy@PeppaTypoPig.com <suzzy@peppapig.com>',
  undefined,
  'suzzy@peppapig.com',
  index: 0,
  input: 'Suzzy@PeppaTypoPig.com <suzzy@peppapig.com>',
  groups: undefined
]
> elonsEmail.match(emailRegex)
[
  'Elon Musk <42069@tesla.com>',
  undefined,
  '42069@tesla.com',
  index: 0,
  input: 'Elon Musk <42069@tesla.com>',
  groups: undefined
]

and I don't want to refere once to email with .match(emailRegex)[1] and .match(emailRegex)[2] in other cases. I'm sure there is a better way.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
noisy
  • 6,495
  • 10
  • 50
  • 92
  • See [regex extract email from strings](https://stackoverflow.com/a/42408099/3832970) – Wiktor Stribiżew Aug 18 '21 at 10:58
  • Almost: https://regex101.com/r/jwviF0/1 – mplungjan Aug 18 '21 at 11:02
  • @WiktorStribiżew your linked solution doesn't work here. It would return 2 emails from "Suzzy@PeppaTypoPig.com ", where it should return only 2nd. I would appriciate "This question already has answers here:", as this is not true in that case. – noisy Aug 18 '21 at 11:11
  • It you want a single match, just remove the `g` flag, the regex pattern in the linked solution is working for your examples. If you need to remove duplicate results, use a `Set`. – Wiktor Stribiżew Aug 18 '21 at 11:13
  • @WiktorStribiżew Maybe we talking about different regex? Regex which I took from your link: https://regex101.com/r/0Q8ATb/1/ extract first email. How it could do a different thing? Where it do not prioritize email address between angle brackets in any way. – noisy Aug 18 '21 at 11:37
  • "Prioretizing" is the keyword. It can be done with a bit of capturing, like [here](https://regex101.com/r/0Q8ATb/2) – Wiktor Stribiżew Aug 18 '21 at 11:41
  • well... this returns very similar results like mine original regex. Here is your suggested solution: https://gist.github.com/noisy/4c33ef5f3906d14b7f7ddd4c1c08c243. Problem is... that sometimes I would need to do refer to results as match(...)[1] and in other cases match(...)[2] – noisy Aug 18 '21 at 12:13

0 Answers0