-5

I want to validate url with port so i need regular expression to validate it. Currently I am using this expression.

NSString *urlRegEx =@"(?i)(?:(?:https?|http):\\/\\/)?(?:\\S+(?::\\S*)?@)?(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?";

but it is not validating sometimes.

Eimantas
  • 48,927
  • 17
  • 132
  • 168
Aadil Ali
  • 351
  • 1
  • 15

1 Answers1

2

Here's how I'd do it:

Let's take an URL:

https://some.long.domain.with.subdomains.com:12345/otherpath?queryparam=queryvalue

Let's initialise NSURL with this string:

NSURL *url = [NSURL URLWithString:theStringFromAbove];

If URL is invalid, the url variable will be nil. Otherwise, grab a port and check if it's what we need:

if (!url || [url port] != 12345) {
    NSLog(@"YOU SHALL NOT PASS");
}
Eimantas
  • 48,927
  • 17
  • 132
  • 168