Home > Back-end >  RegEx to validate URL patterns
RegEx to validate URL patterns

Time:10-06

RegEx to validate URL patterns

I need help with a regular expression to validate any of the following URL patterns. The * is a wildcard.

https://google.com
https://www.google.com
https://www.google.com/*
https://*.google.com/
https://*.google.com/asdasdas/*

So far I have this:

https:\/\/(w{3}|\*)?(?:\.[\w\.-] ){2,}[\w\-\._~:/?#[\]@!\$&'\(\)\?:(*)\ ,;=.] $

But is failing on the first case, a domain pattern without "www" or "*" before the first dot.

Keep in mind that instead of google.com it could be any domain.

CodePudding user response:

This regex could be the one that you're looking for:

^https:\/\/([\w*] \.){1,2}([\w] \/?) \*?$

CodePudding user response:

This regex will match with the urls you provided and also urls with subdomains:

/^https:\/\/([www]|[*]\.)?[-a-zA-Z0-9@:%._ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_ .~#?&\/\/=].*)?/gmi

You can check the result or the explanation here: https://regex101.com/r/cITjMZ/1

  • Related