Search code examples
javascriptregexbacktracking

Email validation regex takes a long time to complete on medium-long strings


After returning true or false with:

return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/.test(str));

Where str is [email protected] it takes about 25 seconds to complete.

In general, shorter strings take less than 1 second.

This is most likely due to back-tracking. I am not very good with Regex, can someone help me reduce the time it takes to process an email. E.g. it must have letter(s) then @ then letter(s) then . then letter(s) and must not be too long.


Solution

  • Just use

    \S+@\S+
    

    Or even (with anchors)

    ^\S+@\S+$
    

    and actually send an email to that address rather than using a complicated, likely error-prone expression.