简体   繁体   中英

How to write a RegEx for finding name in email address?

Kapil Arora <kapil.arora@abc.in> 

How to find the name before angular bracket

This is the RegEx I used ([^<]+). but it is not finding first String

Since you haven't specified any language. I would be solving in JavaScript.

Lets assume an email id as "kapil.sharma123@gmail.com".

Thus the program would be something like this:

var email = "kapil.sharma123@gmail.com";
var regex = /(^[A-Za-z]+\.+[A-Za-z]+)/;
var res   = email.match(regex)[1];
res = res.split(".").join(" ");

Here I am matching the regex with the email id string and then extracting from the first index. Finally I am spliting on "." and joining with a blankspace.

Note : It also works for simple email ids like "kapil.sharma@gmail.com"

I would just add a start of input anchor ^ to the head of your expression, plus a look ahead for a space so you get just the name (no trailing space):

^[^<]+(?= )

No need for brackets; group 0 is the whole match, which is what you want.

See live demo .

You may try this:

 const regex = /^\\s*([^<]+)\\s*</g; const str = `Kapil Arora <kapil.arora@abc.in> bla bla bla <asadfasdf>`; var match = regex.exec(str); console.log(match[1].trim()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM