0

I looked at this question:

What is a good regular expression to match a URL?

And took the most up-voted answer which is this regex:

^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$

This works great to validate urls, HOWEVER, I also need this to allow strings such as this:

http://www.cool.com:81/index.html?query=${query}&sortBy=${sortBy}

Notice the placeholder strings such as ${query} and ${sortBy} (there can be any letters a-z inside the brackets). These are later replaced with actual values so the final url would look like this:

http://www.cool.com:81/index.html?query=helloworld&sortBy=population

I've been playing around with the regex to see if I can add a condition where those placeholders are allowed but none of my attempts have been successful unfortunately.

How can I do this?

EDIT:

The duplicate question provided does not answer how to match ${query} but rather specific urls that just has parameters.

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • 1
    Possible duplicate of [Regex to match URL with specific query string param](https://stackoverflow.com/questions/37227408/regex-to-match-url-with-specific-query-string-param) – Ignacio Ara Apr 19 '18 at 09:27
  • `^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b((?:[-a-zA-Z0-9@:%_\+.~#?&//=\$\{\}])*)$` – dfsq Apr 19 '18 at 09:34
  • @dfsq: This regex will not work when `=${sortBy}&&` or `}}}}}}` or `$$$$$` – Tan Duong Apr 19 '18 at 09:36
  • @TanDuong I know, but I'm not answerging question. Original regexp is not good to start with. – dfsq Apr 19 '18 at 09:42
  • @IgnacioAra I don't see how this is a duplicate of that question. I'm asking a completely separate thing. – Chrillewoodz Apr 19 '18 at 10:14
  • Do you want to match a url exactly like this: http:// *domain* / *path* ${query}&sortBy=${sortBy} ? or inside curly braces could be "anything"? – alsjflalasjf.dev Apr 19 '18 at 10:27
  • You need to validate an URL with params, you just need to adapt the REGEX for `a\=` with your `query\=` and `sortBy=` – Ignacio Ara Apr 19 '18 at 10:27
  • @siete.sh It can be anything inside the brackets. – Chrillewoodz Apr 19 '18 at 10:42
  • @IgnacioAra It's not just that easy, if you actually tried the proposed solution there you'd find out yourself. It doesn't take into account the placeholders, as well as the fact that the parameters can be named anything as well as the text inside the brackets. – Chrillewoodz Apr 19 '18 at 10:51

1 Answers1

0
^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)\?query=([a-z]+)&sortBy=([a-z]+)$

In Group 3, you have your query, and in Group 4, your sortBy

See it here:

https://regex101.com/r/2pw8Yh/1

alsjflalasjf.dev
  • 1,589
  • 13
  • 11