3

I found this regex for email. I tried to turn it into a multi-line version. But after I do it it stops working:

const emailOne = /^(([^<>()\[\]\\.,;:\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,}))$/

const email = RegExp(
  /* eslint-disable */
  '^(([^<>()\[\]\\.,;:\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,}))$'
  /* eslint-enable */
)

emailOne.test('abc@gmail.com')

emailTwo.test('abc@gmail.com')

emailOne returns true. emailTwo returns false. Why could be the reason?

EDIT:

I realized that RegExp modifies the original regex (breaking it):

// regex created by RegExp
/^(([^<>()[]\.,;: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,}))$/

// emailOne
/^(([^<>()\[\]\\.,;:\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,}))$/
Community
  • 1
  • 1
alex
  • 7,111
  • 15
  • 50
  • 77
  • @Pang Fixed the answer. – alex Nov 24 '16 at 06:26
  • "One-line email regex works" No it doesn't. Your regex excludes a ton of perfectly valid e-mail addresses. http://stackoverflow.com/a/201378/362536 – Brad Nov 24 '16 at 06:29
  • Here is a previous question asking about the same issue with what appears to be the same regex. http://stackoverflow.com/questions/12317049/how-to-split-a-long-regular-expression-into-multiple-lines-in-javascript The accepted answer should do what you need. – jcalton88 Nov 24 '16 at 06:30
  • @Brad It's the first Google result that popped up. I included the link. – alex Nov 24 '16 at 06:30
  • @alex The safest way to validate an email address is to send an email that requests a user action. – Arjan Nov 24 '16 at 06:34

1 Answers1

2

Your first regex is specified with regex. Your second one is specified with strings, and you neglected to escape the backslashes with another backslash. \\

Brad
  • 159,648
  • 54
  • 349
  • 530