0

I have the following Regex code that's taking a long time (30+ seconds) to validate large URLS:

let validReg = new RegExp('^(https?:\\/\\/)?'+ // protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string '(\\#[-a-z\\d_]*)?$','i'); let isValid = validReg.test(component.repository_url); 

How can I change this code to validate the same Regex more efficiently?

5
  • 1
    Why is this tagged as Python? This looks like JavaScript. Commented Mar 6, 2022 at 3:36
  • If it was Python, you'd skip the regex and use a dedicated URL parsing API, e.g. urllib.parse.urlparse. Parsing complicated formats with a regex is typically a terrible idea (even if it works, it's rarely maintainable). Commented Mar 6, 2022 at 3:46
  • @BrokenBenchmark thanks for pointing out the mistake. this is Javascript. Commented Mar 6, 2022 at 7:04
  • 1
    Since it is JavaScript one would use parser based approaches as well ... the Web API provides URL and URLSearchParams Commented Mar 6, 2022 at 11:33
  • 1
    Does this answer your question? What is the best regular expression to check if a string is a valid URL? Commented Mar 6, 2022 at 13:42

1 Answer 1

1

You need to refactor the part where you match hyphen separated word chars: [a-z\\d]([a-z\\d-]*[a-z\\d])* => [a-z\\d]+(?:-+[a-z\\d]+)*.

Also, note you do not need to escape / chars, they are not special regex metacharacters, and you are not using a regex literal.

You may use

let validReg = new RegExp('^(https?://)?'+ // protocol '((([a-z\\d]+(?:-+[a-z\\d]+)*)\\.)+[a-z]{2,}|'+ // domain name '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address '(:\\d+)?(/[-a-z\\d%_.~+]*)*'+ // port and path '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string '(#[-a-z\\d_]*)?$','i'); let isValid = validReg.test(component.repository_url); 
Sign up to request clarification or add additional context in comments.

2 Comments

@Travis This alone won't crash anything. What was the input string?
Actually you're right, I am unable to get it to crash now, so I must have made an error on my end. My apologies!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.