web-dev-nerd
web-dev-nerd

Reputation: 31

Improving Regexp performance

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?

Upvotes: 0

Views: 226

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

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);

Upvotes: 1

Related Questions