1

From research of the same,i came to find none of the suggested URL's matching my criteria, thus raised a new query.

Following are my requirements : * The URL may or may not contain a 'http' or 'https' * The URL can be directly an IP address with a port number.

Examples that should pass:

Invalid Urls:

Aishwarya
  • 71
  • 1
  • 10

1 Answers1

4

With the provided input strings/examples, I could come up with the following regex. It is long but it does cover the scenarios mentioned by you.

Regex:

^(?![^\n]*\.$)(?:https?:\/\/)?(?:(?:[2][1-4]\d|25[1-5]|1\d{2}|[1-9]\d|[1-9])(?:\.(?:[2][1-4]\d|25[1-5]|1\d{2}|[1-9]\d|[0-9])){3}(?::\d{4})?|[a-z\-]+(?:\.[a-z\-]+){2,})$

Click for DEMO

EXPLANATION:

  • ^ - Start of the string
  • (?![^\n]*\.$) - Negative Lookahead to validate that the string does not end with .
  • (?:https?:\/\/)? - Optional http:// or https://
  • (?:[2][1-4]\d|25[1-5]|1\d{2}|[1-9]\d|[1-9])(?:\.(?:[2][1-4]\d|25[1-5]|1\d{2}|[1-9]\d|[0-9])){3}(?::\d{4})? - Regular expression for a valid IP address followed by an optional port number(:XXXX)
  • | - OR
  • [a-z\-]+(?:\.[a-z\-]+){2,} - To match strings like flower.insu-rge.ui
  • $ - End of String
Gurmanjot Singh
  • 8,936
  • 2
  • 17
  • 37
  • I used the above regex in my typescript file but still i m getting a mismatch on all the examples that i have stated above. – Aishwarya Sep 19 '17 at 12:26
  • I did : let urlRegex = '(?![^\n]*\.$)(?:https?:\/\/)?(?:(?:[2][1-4]\d|25[1-5]|1\d{2}|[1-9]\d|[1-9])(?:\.(?:[2][1-4]\d|25[1-5]|1\d{2}|[1-9]\d|[0-9])){3}(?::\d{4})?|[a-z\-]+(?:\.[a-z\-]+){2,})'; and checked control.value.match(urlRegex) : this returns invalid status – Aishwarya Sep 19 '17 at 12:27
  • you can further test the regex from regex101.com – Ali Sajid Sep 20 '17 at 07:43
  • the same regex used on multiple regex test platforms gives appropriate results,I am not able to use this in my typescript class, am i doing something wrong,syntax wise? – Aishwarya Sep 20 '17 at 09:06
  • I could only help you with the regex as I am not familiar with the typescript syntax. This regex even works for Javascript flavor(as can be seen here - https://regex101.com/r/ywrtaN/2). – Gurmanjot Singh Sep 20 '17 at 09:12
  • Yes it does work there too, i am not able to figure out why this regex is returning invalid with the same examples that are passed by the javascript flavor. – Aishwarya Sep 20 '17 at 09:21
  • The URL worked, i needed to enclose the regex with '/gm' flag, which i didn't before. – Aishwarya Sep 21 '17 at 07:14