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)
    }
3

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

its return me error "Invalid escape sequence in literal" in swift 2.0
@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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.