1

In Google Chrome, this successfully matches the email address:

console.log('teddy@bear.com'.match(/^(([^<>()\[\]\\.,;:\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,}))$/));

and this does not:

const regex = '^(([^<>()\[\]\\.,;:\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,}))$';
console.log('teddy@bear.com'.match(regex));

The only difference is that the latter has the regular expression passed in through a variable and not using the forward slashes.

I wonder how to get the latter work.

bjfletcher
  • 11,168
  • 4
  • 52
  • 67
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp Pass it as a Regex Expression object? – Aleksandar Misich Mar 23 '17 at 16:41
  • You need to escape all the backslashes to keep them literal in the string. You got it right in a few places where you wrote `\\.`, but you missed it in most other places. – Barmar Mar 23 '17 at 16:42
  • It's because a backslash in a string is interpreted first : the value of your regexp string is: ^(([^<>()[]\.,;: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,}))$ – Tom Mar 23 '17 at 16:42

1 Answers1

1

When you use a string, the backslashes are interpreted as escape sequences when the string literal is being read, and they're not passed through to the RegExp constructor. You need to escape them to keep them in the string.

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

I'm not sure why you want to do this using a string literal. If you want to put the regexp in a variable, you can still use a RegExp literal.

const regex = /^(([^<>()\[\]\\.,;:\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,}))$/;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks for the answer, that works great! :) To answer your question regarding using a string literal, it's because the list of regular expressions come as strings from a config file. :) – bjfletcher Mar 23 '17 at 17:18
  • If they come from a config file, then escaping isn't an issue. Escapes are only processed when the string is a literal in source code, not when it's read from a file. – Barmar Mar 23 '17 at 17:20
  • Are you reading the file in a server-side language, and then using it to create the Javascript source code? In that case, you should probably use the language's JSON function to format the string properly. – Barmar Mar 23 '17 at 17:21
  • If you want to know the proper way to do it, post the code that's actually having the problem. – Barmar Mar 23 '17 at 17:22