3

How a string object can be validate whether it is a link or not? I don't want to open any connection or network operation I just to want to check the pattern of string is matching to the pattern of a link or not. e.g

    let str1 = "https://stackoverflow.com/questions/ask" // It is a link
    let str2 = "https://stackoverflow.com" // It is a link
     // Could be other combinations as well of a valid link 
    let str3 = "this is not a link" // Not a link

How to do that? Is It possible to check with regular expression or any other way or not possible?

Afsar edrisy
  • 1,828
  • 7
  • 20

1 Answers1

3

You can do the check with URL initializer that returns optional value. Example

let str1 = "https://stackoverflow.com/questions/ask"
if let url = URL.init(string: str1) {
        // It will pass            
}

let str2 = "not a link"
if let url = URL.init(string: str2) {
        // It will not pass            
}

You can do exactly the same with guard let - else { }

Βασίλης Δ.
  • 1,326
  • 10
  • 18