javascript - Performance issue while evaluating email address with a regular expression -
i using below regular expression validate email address.
/^\w+([\.-]?\w+)*@\w+([\.-]?w+)*(\.\w{2,3})+$/
javascript code:
var email = 'myname@company.com' var pattern = /^\w+([\.-]?\w+)*@\w+([\.-]?w+)*(\.\w{2,3})+$/ if(pattern.test(email)){ return true; }
above regular expression evaluates email address when provide below invalid email address.(i have added #$ in middle of name)
aseflj#$kajsdfklasjdfklasjdfklasdfjklasdjfaklsdfjaklsdjfaklsfaksdjfkasdasdklfjaskldfjjdkfaklsdfjlak@company.com
but when try evaluate below email address takes , browser gets hanged. (i have given com1 in end)
asefljkajsdfklasjdfklasjdfklasdfjklasdjfaklsdfjaklsdjfaklsfaksdjfkasdasdklfjaskldfjjdkfaklsdfjlak@company.com1
i sure regular expression correct not sure why taking time evaluate second example. if provide email address shorter length evaluates quickly. see below example
dfjjdkfaklsdfjlak@company.com1
kindly me fix performance issue.
your regex runs catastrophic backtracking. since [\.-]?
in ([\.-]?\w+)*
optional, makes group degenerates (\w+)*
, classic case of catastrophic backtracking.
remove ?
resolves issue.
i remove redundant escape of .
inside character class, , changed regex bit.
^\w+([.-]\w+)*@\w+([.-]\w+)*\.\w{2,3}$
do note many new generic tlds have more 3 characters. of gtld before expansion have more 3 characters, such .info
.
and is, regex doesn't support internationalized domain name.