0

I am trying to validate an URL in Swift 3 but I can't seem to find the Regex that suits my needs. Regex that I am after needs to accept following combinations:

http://google.com
http://google.com/foo/bar:30/35
https://google.com
https://google.com/foo/bar:30/35
www.google.com
google.com
9
  • 4
    When I Google Validate URL in swift 3.0 I seem to get a lot of results. None, apparently, are Swift 3 specific, but they come with the regex you need and should be easy enough to port. E.g. stackoverflow.com/questions/29106005/url-validation-in-swift
    – Pekka
    Oct 12, 2016 at 10:59
  • I don't see why question has downvotes Oct 12, 2016 at 11:42
  • 1
    Questions that are this easily Google-able should really be Googled first. When then you encounter a specific problem, or all of the available solutions don’t work, then it may be worth asking a question (mentioning what you’ve tried that far.)
    – Pekka
    Oct 12, 2016 at 12:06
  • 3
    @Pekka웃 That's against the idea of the site. If there is a duplicate answer, sure, link to that. But just because something is Google-able doesn't mean it is not a valid question. Many Google results hit stackoverflow.com, which would not be the case had someone not asked here.
    – sdasdadas
    Oct 12, 2016 at 15:51
  • 1
    Fyi, I stumbled across this answer while Googling for a solution to this precise problem and I'm still wondering what's the best way to validate a URL in Swift. Regex is not Swift specific, so this question is still relevant - even if the answer is that there's no Swift-specific mechanism to validate URLs. Apr 23, 2019 at 14:21

1 Answer 1

6
func validateUrl (urlString: NSString) -> Bool {
    let urlRegEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
    return NSPredicate(format: "SELF MATCHES %@", urlRegEx).evaluateWithObject(urlString)
}

This worked.

2
  • 2
    This still doesn't accept subdomains. For example, google.basecamp.com would return false. Any help? Oct 17, 2016 at 12:07
  • 1
    this regex covers most of the cases "(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/?)(?:[^\\s()<>]+|\(([^\\s()<>]+|(\([^\\s()<>]+\)))*\))*(?:\(([^\\s()<>]+|(\([^\\s()<>]+\)))*\)|[^\\s`!()\[\]{};:'\".,<>?«»“”‘’])*)" Jul 11, 2018 at 0:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.