0

I have this regex for matching email addresses in a string.

[a-zA-Z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-zA-Z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,})

It is not the best regex in the world but good enought for my use.

When I am using this with javascript like that:

var emails = string.match("[a-zA-Z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-zA-Z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,})");

I am matching only the first email address, which is normal because I am not using the g modifier.

The problem is that when I am using the g modifier like that:

var emails = email[0].match("[a-zA-Z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-zA-Z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,})g");

the var emails is null, so my match is not working.

If you can please help me with this.

Thank you.

Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265
  • please provide a real example to test on i did not get the g part well – shareef Jul 04 '12 at 07:40
  • may be duplicate of [How to use a regular expression to validate an email addresses?](http://stackoverflow.com/questions/201323/how-to-use-a-regular-expression-to-validate-an-email-addresses) – Ria Jul 04 '12 at 07:55

2 Answers2

5

Try :

var emails = yourString.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • Thank you Sudhir, your example works wery well. I have try it. – Milos Cuculovic Jul 04 '12 at 07:46
  • hi can you provide a link to learn regexp and a tool to facilate it and is javascript regexp same as java match method as syntax i mean please answer me :) – shareef Jul 04 '12 at 10:15
  • Well, you can learn regexs refering to this site:: http://www.regular-expressions.info/ , i dont know Java, but the pattern should be the same only functions using those patterns vary on different languages.. – Sudhir Bastakoti Jul 04 '12 at 10:30
1

try this i used it in servlet validation filter in my system i dont know if it works in javascript

"^[a-zA-Z0-9._]+@[a-zA-Z0-9._]{3,}$"
shareef
  • 9,255
  • 13
  • 58
  • 89