0

I have a lot of strings with pattern like that

/ucwa/oauth/v1/applications/101507538841/people/adan.maddox@dc.com/presence

How can I use regex to get email like adan.maddox@dc.com

I tried this code, and its working but I feel it's not a good way.

    var y = myString.substring(0, myString.lastIndexOf("/presence"));
    var email = y.substring(y.lastIndexOf("people/") + 7);
Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
Tarek Saied
  • 6,482
  • 20
  • 67
  • 111
  • Try matching with this regex http://stackoverflow.com/questions/46155/validate-email-address-in-javascript – elclanrs Sep 29 '13 at 00:01
  • @elclanrs thanks , but i do't need to validate the email address , i need only to get them from string with this pattern – Tarek Saied Sep 29 '13 at 00:04
  • Same thing, you can use same regex to validate and match, just remove the start and end characters and it should be good. – elclanrs Sep 29 '13 at 00:07

3 Answers3

6

Your way will probably work consistently. If you were looking for a more-or-less equivalent regular expression to make it more clear, it might be:

var re = /\/people\/([^/]+)\/presence/;
var email = re.exec(myString)[1];
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 1
    This is much safer. Most email regexes are simplified and will sometimes have false positive and false negatives. Since weird stuff like this `"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com` is a valid [email address](http://en.wikipedia.org/wiki/Email_address). – Kerry Liu Sep 29 '13 at 00:11
  • @KerryLiu: `"do not forget "(comments).+@[::1]` – Ry- Sep 29 '13 at 00:14
2

Use match:

var str = "/ucwa/oauth/v1/applications/101507538841/people/adan.maddox@dc.com/presence";
var n = str.match(/[A-Za-z\.]+@[A-Za-z\.]+/);

http://jsfiddle.net/SnZxP/

George Newton
  • 3,153
  • 7
  • 34
  • 49
  • 1
    Unfortunately, emails can be lot more complex (Google: email regexp). If order of elements is fixed, @minitech's solution is probably the best. – Tadeck Sep 29 '13 at 00:08
0

The following is a bit saver:

var str = "/ucwa/oauth/v1/applications/101507538841/people/adan.maddox@dc.com/presence";
var n = str.match(/[^\/]*@[^\/]*/);

This way, the pattern of your email address doesn't really matter too much and you don't have to worry about the position of the email address in your string...

This probably matches best to your pattern.

If you want to extract more than one email addresses out of your pattern you could even go for:

var n = str.match(/[^\/]*@[^\/]*/g);

So, even the weird address mentioned before:

var str = 'ucwa/oauth/v1/applications/101507538841/\"very\".unusual"@strange.example.com/people/adan.maddox@dc.com'

Would bring you an array:

[""very".unusual"@strange.example.com", "adan.maddox@dc.com"]

See: http://jsfiddle.net/SnZxP/2/

jsmorph
  • 221
  • 1
  • 5