Regular expression to get URL in string swift with Capitalized symbols

You turn off case sensitivity using an i inline flag in regex, see Foundation Framework Reference for more information on available regex features.

(?ismwx-ismwx)
Flag settings. Change the flag settings. Changes apply to the portion of the pattern following the setting. For example, (?i) changes to a case insensitive match.The flags are defined in Flag Options.

For readers:

Matching an URL inside larger texts is already a solved problem, but for this case, a simple regex like

(?i)https?://(?:www\\.)?\\S+(?:/|\\b)

will do as OP requires to match only the URLs that start with http or https or HTTPs, etc.


Swift 4

1. Create String extension

import Foundation

extension String {

    var isValidURL: Bool {
        guard !contains("..") else { return false }
    
        let head     = "((http|https)://)?([(w|W)]{3}+\\.)?"
        let tail     = "\\.+[A-Za-z]{2,3}+(\\.)?+(/(.)*)?"
        let urlRegEx = head+"+(.)+"+tail
    
        let urlTest = NSPredicate(format:"SELF MATCHES %@", urlRegEx)

        return urlTest.evaluate(with: trimmingCharacters(in: .whitespaces))
    }

}

2. Usage

"www.google.com".isValidURL

Tags:

Ios

Regex

Swift