0

We are using below regular expression to validate email address in java ^[\\w!#\\$'\\*\\+=\\?\\^\\/_~-]+(\\.[\\w!#\\$'\\*\\+=\\?\\^\\/_~-]+)*@([a-zA-Z0-9\\-]+\\.)+[A-Z]{2,4}$ and it worked fine with invalid email address raju.rathi@gmail.com&^(*&^(*^2 but when I use the same regular expression in javascript , it doesn't work and failes with even valid email addresses . Please suggest what could be root cause of this mismatch?

for e.g. in javascript , I'm getting false value with below test conditional -

/^[\w!#\$'\*\+=\?\^\/~-]+(\.[\w!#\$'\*\+=\?\^\/~-]+)*@([a-zA-Z0-9\-]+\.)+ [A-Z]{2,4}$/.test("raju.rathi@gmail.com")

Vivek Pradhan
  • 4,777
  • 3
  • 26
  • 46
Raj
  • 1,698
  • 4
  • 22
  • 39
  • Why don't you use a dedicated API for this (mailapi)? – fge Oct 27 '14 at 09:54
  • possible duplicate of [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Qantas 94 Heavy Oct 27 '14 at 09:59
  • 1
    sorry but it is not a duplicate . i can google and get regex from internet but my requirement is to use same regrx as used in java program which is not working . – Raj Oct 27 '14 at 10:03

2 Answers2

3

You need to convert \\ to \ in Javascript regex literal:

/^[\w!#$'*+=?^\/~-]+(\.[\w!#$'*+=?^\/~-]+)*@([a-zA-Z0-9-]+\.)+[A-Z]{2,4}$/i.test("raju.rathi@gmail.com")

Also many special regex characters like $, +, * etc. don't need to be escaped inside character class hence I have removed unnecessary escaping from your character class.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • /^[\w!#$'*+=?^\/~-]+(\.[\w!#$'*+=?^\/~-]+)*@([a-zA-Z0-9-]+\.)+[A-Z]{2,4}$/.test("raju.rathi@gmail.com") - still i'm getting false when i ran this in java script console – Raj Oct 27 '14 at 09:59
  • 1
    **[It works here](http://regex101.com/r/eD6lW1/1)** Make sure you use `i` (ignore case) flag. – anubhava Oct 27 '14 at 10:04
0

Try this, it works for me.

/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$/.test('raju.rathi@gmail.com');

<html>

<body>
  <script>
    var flag = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$/.test('raju.rathi@gmail.com');
  </script>
  <h5><script>document.write(flag)</script></h5>
</body>

</html>
ajitksharma
  • 4,523
  • 2
  • 21
  • 40