I wrote url validation regex but the regex is very slow

Viewed 37

I know this is slow because of ([\.\-][a-z0-9])*. But I don't know how to optimize it.

^https:\/\/([a-z0-9]+([\.\-][a-z0-9])*)+(\.([a-z]{2,11}|[0-9]{1,5}))(:[0-9]{1,5})?(\/.*)?$
1 Answers

You don't have to use this part )*)+ in your pattern. This could also potentially lead to catastrophic backtracking.

Note that you only have to escape the backslash if the delimiters for the regex are also / and you don't have to escape the [\.\-]

If you don't need that capture groups afterwards, you can omit them.

^https:\/\/[a-z0-9]+(?:[.-][a-z0-9]+)*\.(?:[a-z]{2,11}|[0-9]{1,5})(?::[0-9]{1,5})?(\/.*)?$

The pattern matches:

  • ^ Start of string
  • https:\/\/ Match https:// As you only want to match https
  • [a-z0-9]+ Match 1+ times any of the listed
  • (?:[.-][a-z0-9]+)* Optionally repeat matching . or - and 1+ times any of the listed
  • \.(?:[a-z]{2,11}|[0-9]{1,5}) Match either 2-11 times a char a-z or match 1-5 digits
  • (?::[0-9]{1,5})? Optionally match : and 1-5 digits
  • (\/.*)? Optionally match /` and the rest of the line
  • $ End of string

Regex demo

Related