search

Home  >  Q&A  >  body text

Title rewritten as: "Regular expression that works when using the u flag, but not when using the v flag"

<p>I encountered the following console warning in this regex pattern: </p> <pre class="brush:php;toolbar:false;">^[a-zA-Z0-9 _.-] @[a-zA-Z0-9] \\.[a-zA-Z0- 9] $</pre> <blockquote> <p>Pattern attribute value <code>^[a-zA-Z0-9 _.-] @[a-zA-Z0-9] \.[a-zA-Z0-9] $</code> ; is valid with the RegExp <code>u</code> flag, but not with the <code>v</code> flag: Uncaught SyntaxError: Invalid regular expression: <code>/^[a-zA- Z0-9 _.-] @[a-zA-Z0-9] \</code>.<code>[a-zA-Z0-9] $/v:</code> There are Invalid character. </p> </blockquote> <p>I can't see how to create a valid regex pattern to resolve this warning. Could anyone please explain the error and how to fix it? </p> <p>Trying to look at the documentation but can't find how to make it work with the <code>v</code> flag. </p>
P粉684720851P粉684720851486 days ago551

reply all(1)I'll reply

  • P粉116631591

    P粉1166315912023-08-26 13:50:46

    The problem is that the newly introduced v flag imposes more restrictions on escaping rules. Since it allows subtraction and intersection of character classes, the literal - at the end of the character class cannot remain unescaped.

    Therefore, if you use the u flag, there is no such restriction, and if you use the v flag, there is such a restriction. See.

    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"))

    reply
    0
  • Cancelreply