1

IN Swift i am using regular expression for checking "WWW" and "HTTP" Both , But in my code its only check for http when i put "www.google.com" then its show not valid please give me solution.Here is my code. how to check url when we not put http.

 func validateUrl (stringURL : NSString) -> Bool {

        let urlRegEx = "(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*)+)+(/)?(\\?.*)?"
        let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx])
        let urlTest = NSPredicate.predicateWithSubstitutionVariables(predicate)
        print(urlTest);
        return predicate.evaluateWithObject(stringURL)
    }
  • 1
    This question has a good answer on validing URLs in Swift: http://stackoverflow.com/questions/28079123/how-to-check-validity-of-url-in-swift – Dan O'Leary Jan 18 '16 at 13:19
  • i don't want to open the url on safari i have to check validation in text field – Nishant Chandwani Jan 18 '16 at 13:40
  • 1
    Possible duplicate of [Extract links from string optimization](http://stackoverflow.com/questions/29496821/extract-links-from-string-optimization) – Victor Sigler Jan 18 '16 at 14:42

1 Answers1

1

You can try a regex similar to this:

(http:\/\/)?w{3}\.[^\s]*\.[a-zA-Z]{2,3}
  • (http:\/\/)?: http can appear 0 or 1 times.
  • w{3}: www
  • \.[^\s]*: dot character followed by any number of other characters except for space
  • \.[a-zA-Z]{2,3}: dot character followed by 2 or 3 letters

I'm not sure that it covers all cases but it will give you a good starting point to do some tests and refactor. It also doesn't cover illegal URL characters.

Artal
  • 8,933
  • 2
  • 27
  • 30
  • its return me error "Invalid escape sequence in literal" in swift 2.0 – Nishant Chandwani Jan 19 '16 at 06:01
  • @user3899589 yes, well this is the raw form of the regex. To use it in your code you'll need to escape it like you did in your original expression (use \\. Instead of \. and so on) – Artal Jan 19 '16 at 07:02