0

I am trying to validate a form. When validating a url field, I need to make sure, that the user provides a string without http(s):// but may use www. as well as strings such as xyz.abc.com - note the two dots.

I tried using

UIApplication.sharedApplication().canOpenURL(url)

but this applies to me having https:// written.

Also I tried this regex from here

    let regEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"

after deleting the first part, I don't seem to get the multiple dots working.

JVS
  • 2,592
  • 3
  • 19
  • 31

1 Answers1

1

You could use negative lookbehind :

let regEx = "(?<!((https|http)://))((\\w|-)+)(([.]|[/])((\\w|-)+))+"

So given these strings :

let string1 = "https://www.google.com"
let string2 = "stackoverflow.com/questions/54269877/regex-for-specific-urlfield"

The result of evaluating them with the same predicate :

let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[regEx])

would yield the expected results :

predicate.evaluate(with: string1)  //false
predicate.evaluate(with: string2)  //true
ielyamani
  • 17,807
  • 10
  • 55
  • 90