Search code examples
javascriptregexsafaribacktracking

Regex fails only on Safari


I have the following simple email validation regex: /(.+){2,}@(.+){2,}\.(.+){2,}/

This works fine on Firefox, Chrome etc, but fails on Safari.

Why would this perfectly valid regex fail on Safari? I could not find elements in the regex that are not supported by Safari.

/(.+){2,}@(.+){2,}\.(.+){2,}/.test('123@abc.nl');

Above fails on Safari, but not on any other browser.


Solution

  • Different regex engines have different tolerance to catastrophic backtracking prone patterns.

    Yours is a catastrophic backtracking prone pattern as you quantify (.+) with the {2,} quantifier that makes (.+) match two or more times (that is, match one or more times twice or more, which makes it fail very slowly with non-matching patterns.)

    If you meant to match any two or more chars, quantify the . pattern and not a .+ one:

    /.{2,}@.{2,}\..{2,}/
    

    Or, use existing email validation patterns..