7

I am getting the below console warning for this regex pattern:

^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+$

Pattern attribute value ^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$ is valid with the RegExp u flag, but not with the v flag: Uncaught SyntaxError: Invalid regular expression: /^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/v: Invalid character in character class.

I can not see how to create a valid regex patter for this warning. Please, could somebody explain the error and how to resolve it?

Tried looking at documentation, but could not see how to make it valid for the v flag

DSDmark
  • 1,045
  • 5
  • 11
  • 25
DuckSoup
  • 91
  • 5

1 Answers1

8

The issue is that the newly introduced v flag applies even more restrictions to escaping rules. Since it allows character class subtraction and intersection, the literal - at the end of a character class cannot be left unescaped.

So, if you use the u flag, there is no such a restriction, with the v flag, it is in place. Cf.

console.log(/^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/u.test("myname@somesite.com"))
console.log(/^[a-zA-Z0-9+_.\-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/v.test("myname@somesite.com"))

So, always escape literal hyphens inside character classes in ECMAScript patterns.

Here are more details on which patterns are now considered invalid:

Some previously valid patterns are now errors, specifically those with a character class including either an unescaped special character ( ) [ { } / - | (note: \ and ] also require escaping inside a character class, but this is already true with the u flag) or a double punctuator:

[(]
[)]
[[]
[{]
[}]
[/]
[-]
[|]
[&&]
[!!]
[##]
[$$]
[%%]
[**]
[++]
[,,]
[..]
[::]
[;;]
[<<]
[==]
[>>]
[??]
[@@]
[``]
[~~]
[^^^]
[_^^]
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Good to know. This subsection in the link you've given specifically talks about the issue at hand: [How is the v flag different from the u flag?](https://github.com/tc39/proposal-regexp-v-flag#how-is-the-v-flag-different-from-the-u-flag). – oriberu May 19 '23 at 09:50
  • @oriberu I added these pertinent details to the question, that will be surely helpful. – Wiktor Stribiżew May 19 '23 at 10:17