-1

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.

andy_314
  • 431
  • 5
  • 17
  • Possible duplicate of https://stackoverflow.com/a/190405/795683 – Sain Pradeep Oct 06 '22 at 10:28
  • @SainPradeep no, that response doesnt cover the wildcard cases that I have. Thanks anyway – andy_314 Oct 06 '22 at 10:30
  • try this https:\/\/(w{3}|\*)?(?:\.?[\w\.-]+){2,}[\w\-\._~:\/?#[\]@!\$&'\(\)\?:(*)\+,;=.]+$ – Sain Pradeep Oct 06 '22 at 10:47
  • It's not clear what you're aiming to do exactly, but I might add that `JavaScript` has a [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) object that you could use to validate/parse `URL`s. – ThS Oct 06 '22 at 10:54

2 Answers2

1

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

^https:\/\/(((www)|\*)\.)?([\w*]+\.)([\w]+\/?)+\*?$
0

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

  • Thanks but is not validating the www part properly. For example, with your solution ww.google.com or wqwe.google.com are true – andy_314 Oct 06 '22 at 11:46
  • Actually they can be valid addresses, for example "[https://url.spec.whatwg.org/](https://url.spec.whatwg.org/)" is a valid URL and does not have the classic "www". As a solution it is a bit more universal, but if it is not what you are looking for, the answer of @cristiano-schiaffella is right for your case – Gurpreet Surinder Singh Oct 07 '22 at 12:19