-1

I'm using the following regular expression.

regForUrl =/^((ftp|http|https):\/\/)(?:(www+\.)?)(?:([a-zA-Z0-9-]+\.))+([a-z]{2,3}\/)+(?:[\w\-\.\_\__\~\:\/\?\#\@\!\$\,\;\*\$\(\)\&\=\+\:\%]?)+$/;

Example URL = 'http://test.domainName.com.ab:5445/endUrl'.

This regex not accepting the above mentioned URL. If ":" occurs the regex returning false. Please solve this issue...

Emre Koc
  • 1,481
  • 10
  • 18
  • 1
    You are not matching the port `:5445` – The fourth bird Aug 13 '20 at 08:25
  • Does this answer your question? [What is the best regular expression to check if a string is a valid URL?](https://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url) – Antoine Aug 13 '20 at 08:43
  • 1
    Might want to use a tool like https://regex101.com/ to test your code more easily – Emre Koc Aug 13 '20 at 08:47
  • Have a look at [RFC 3987](http://www.faqs.org/rfcs/rfc3987.html) – Toto Aug 13 '20 at 09:23

2 Answers2

0

This works:

^((ftp|http|https):\/\/)(?:(www+.)?)(?:([a-zA-Z0-9-]+.))+([a-z]{2,3})+(?:[\w-._~:/?#@!$,;*$()&=+:%]?)$

But I'm not sure what you are trying to do with this.

  • Why all these useless capture groups? What is the purpose of `([a-z]{2,3})+` in your regex, that doesn't make sense? Why the last non capture group for only 1 character? `www+` matches `wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww` (not an error but ?) – Toto Aug 13 '20 at 09:14
  • @Toto, you are right. I saw these and other... weird expressions. I just limited to fix the original regex. That's why I said "I'm not sure what you are trying to do with this". – Daniel Gonzabay Aug 15 '20 at 04:16
0
^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$

This holds good for all these (example.com, www.example.com, http://example.com, https://example.com & any parameters as well).

ZakirK
  • 25
  • 5
  • What about `ftp` protocol? Why a capture group for single `s`? Your regex matches `.......` or `-.~~!`, not sure these are valid URL. Have look at [RFC 3987](http://www.faqs.org/rfcs/rfc3987.html) – Toto Aug 15 '20 at 08:40