Match the email address that precedes a specific word

I have a regex to match email addresses in javascript. Let's look at an example:

var email = " aaa@bbb.com (A,B); ccc@ddd.com (C,D); eee@fff.com (E,F);"; var emails = email.match(/([a-zA-Z0-9._-] +@ [a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); 

This will return me all emails in var emails.

Now I have a line:

 var initials = "(A,B)"; 

And I would like to receive only an email up to initials value;

If var's initials are "(A, B)", then I would like to get only the email address aaa@bbb.com.

Thank you so much for your help!

+4
source share
2 answers

JavaScript:

 var input = " aaa@bbb.com (A,B); ccc@ddd.com (C,D); eee@fff.com (E,F);"; var initials = "(A,B)"; var email = input.match(new RegExp("([a-zA-Z0-9]+(?:[-._][a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*)(?=\\s*" + initials.replace(/([()])/g, "\\$1") + ")"))[0]; print(email); 

Conclusion:

 aaa@bbb.com 

Check out this code here .

+1
source

Whether you have something like " example@mail.com (A, B)" or like this ((A, B) example@mail.com ", all you have to do is have the first and last part the only capture records. Therefore (A, B) should be automatically excluded to capture the regular expression.

If this is not a problem, you can always take the text returned by the regular expression and use replace to change (A, B) to nothing like this:

 var regexresult=str.replace("(A,B)",""); 

This code will delete the line if it is present, otherwise it will do nothing.

-1
source

All Articles