Regex for parsing name and email from one line

I need to parse the name and email address from a string like
Ansh Aryan < ansharyan@mailinator.com >

I need a regular expression to use in javascript for this purpose, so I get
name = Ansh Aryan
email = ansharyan@mailinator.com

+4
source share
1 answer

You can use the following regular expression:

/([^<]+)\s<(.*)>/ 

Of course, if some deviation from this pattern should be allowed, you will have to configure it to reflect it, but if not, then everything will be fine.

Some brief explanation of regex:

  • ([^<]+) . Match and lock everything until the < symbol is found.
  • \s : Match, but do not commit, one space token, which may be a space, a tab, or something else.
  • <(.*)> : match <...> and write down what's inside it.

This will give an array of matches , where matches[0] should be the entire input, matches[1] name and matches[2] the email address you are looking for.

+8
source

Source: https://habr.com/ru/post/1399682/


All Articles