0

I would like to validate whether an NSString can be converted to a valid NSURL. I know that using URLWithString will make a URL, but it is not always valid. Additionally, I don't want to make a web call every time my user enters a string to verify the URL as that is not battery/data efficient, and it relies on having an active web connection which is not always the case. I came across this site various URLs, and I am now attempting to copy the regex they used and convert it to NSRegular Expression. I've been using this helpful cheatsheet to try and convert it, but to no avail. I stored the regex as a const like so:

static NSString * const urlPattern = @"_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[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\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS";

I have been attempting to convert this by adding escape characters in front of all special characters listed in the cheatsheet, but it doesn't seem to be working properly. Has anyone here has any luck getting @diegoperini's URL regex to work in Objective-C or Swift using NSRegularExpressions?

arc4randall
  • 3,275
  • 3
  • 27
  • 40
  • Have you checked the answer here: http://stackoverflow.com/questions/1471201/how-to-validate-an-url-on-the-iphone? You can probably replace the regex there with yours – Jack Apr 13 '16 at 14:47
  • Well this regex doesn't work in ios because their are special characters for NSRegularExpression that need to be escaped, and it isn't really working for me. – arc4randall Apr 13 '16 at 15:00
  • Why don't you just use `NSURLComponents` to let you parse your string? – CouchDeveloper Apr 13 '16 at 15:10
  • Ya I looked into that too but I couldn't get it to work as well as diegoperini's at the link in my question, so that's why I'm thinking NSRegularExpression using his pattern is the only way to do it. Feel free to show me otherwise though by posting an answer – arc4randall Apr 13 '16 at 18:45

0 Answers0