6

What I am trying to do is to extract email address out of the string SomeName, First (First.SomeName@usa.mywebsite1.com)

Here is the code that I already tried:

 var stringToSearchIn="SomeName, First (First.SomeName@usa.mywebsite1.com)";


 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

var extractedEmail=re.exec(stringToSearchIn);

The variable extractedEmail in the code returns a null.

Jay Walker
  • 4,654
  • 5
  • 47
  • 53
Foo
  • 4,206
  • 10
  • 39
  • 54

4 Answers4

7

I tried this and failed

...is not a very useful description of what happenned. At a guess, the re failed to find a match. An obvious cause for this is the regex you've used here will only match a string which ONLY contains an email address - remove the end anchors (^,$) from the regex and you'll get your email address.

var re = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
symcbean
  • 47,736
  • 6
  • 59
  • 94
2

No need for a regex here. If the string is always of the format

Name (email)

You can simply use ( as delimiter:

var stringToSearchIn="SomeName, First (First.SomeName@usa.mywebsite1.com)";

var extractedEmail = stringToSearchIn.substr(stringToSearchIn.indexOf('(') + 1).slice(0, -1);
Jay Walker
  • 4,654
  • 5
  • 47
  • 53
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
0

This one works for me.

var searchInThisString ="SomeName, First (First.SomeName@usa.mywebsite1.com) SomeName2, First2 (First2.SomeName2@usa.mywebsite1.com)";

var foundEmails =[];

var emailRegex = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;

var gotcha;

while (match = emailRegex.exec(searchInThisString)){

     //-- store in array the found match email
     foundEmails.push(match[0]);

    //-- remove the found email and continue search if there are still emails
    searchInThisString= searchInThisString.replace(match[0],"")
}

alert(foundEmails.join(" "))

massquote
  • 4,387
  • 1
  • 14
  • 16
-1

Try this regex

@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"

This will accept any of the following:

  • email@email.com
  • email@email.email.com
  • email@email.email.email.com

and so on...

simple-thomas
  • 671
  • 7
  • 20
  • I haven't tested to see if this works, and I'm not going to. It could be a very useful regex, but you haven't explained at all *why* this could be a very useful regex. – zzzzBov Feb 28 '13 at 16:52
  • It won't solve the OP's problem and there are multiple issues with the validation of the address using this - it will only match something which looks vaguely like an email address – symcbean Feb 28 '13 at 16:53