nabiullinas
nabiullinas

Reputation: 1245

Regular expression to get URL in string swift with Capitalized symbols

I try to get URLs in text. So, before, I used such an expression:

let re = NSRegularExpression(pattern: "https?:\\/.*", options: nil, error: nil)!

But I had a problem when a user input URLs with Capitalized symbols (like Http://Google.com, it doesn't match it).

I tried:

let re = NSRegularExpression(pattern: "(h|H)(t|T)(t|T)(p|P)s?:\\/.*", options: nil, error: nil)!

But nothing happened.

Upvotes: 12

Views: 16012

Answers (5)

Arthur Stepanov
Arthur Stepanov

Reputation: 579

My complex solution for Swift 5.x

ViewController:

private func loadUrl(_ urlString: String) {
    guard let url = URL(string: urlString) else { return }
    let request = URLRequest(url: url)
    webView.load(request)
}

UISearchBarDelegate:

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    guard let text = searchBar.text else { return }
    
    if !text.isUrl() {
        let finalUrl = String(format: "%@%@", "https://www.google.com/search?q=", text)
        loadUrl(finalUrl)
        return
    }
    
    if text.starts(with: "https://") || text.starts(with: "http://") {
        loadUrl(text)
        return
    }

    let finalUrl = String(format: "%@%@", "https://", text)
    loadUrl(finalUrl)
}

String extension:

extension String {

    func isUrl() -> Bool {
        guard !contains("..") else { return false }
        
        let regex = "((http|https)://)?([(w|W)]{3}+\\.)?+(.)+\\.+[A-Za-z]{2,3}+(\\.)?+(/(.)*)?"
        let urlTest = NSPredicate(format:"SELF MATCHES %@", regex)
        
        return urlTest.evaluate(with: trimmingCharacters(in: .whitespaces))
    }

}

Upvotes: 0

alegelos
alegelos

Reputation: 2604

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

Upvotes: 6

bikram sapkota
bikram sapkota

Reputation: 1124

Make an exension of string

extension String {
var isAlphanumeric: Bool {
    return rangeOfString( "^[wW]{3}+.[a-zA-Z]{3,}+.[a-z]{2,}", options: .RegularExpressionSearch) != nil
}
}

call using like this

"www.testsite.edu".isAlphanumeric  // true
"flsd.testsite.com".isAlphanumeric //false

Upvotes: 0

Debjit Saha
Debjit Saha

Reputation: 1978

Try this - http?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?

    let pattern = "http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?"
    var matches = [String]()
    do {
        let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0))
        let nsstr = text as NSString
        let all = NSRange(location: 0, length: nsstr.length)
        regex.enumerateMatchesInString(text, options: NSMatchingOptions.init(rawValue: 0), range: all, usingBlock: { (result, flags, _) in
            matches.append(nsstr.substringWithRange(result!.range))
        })
    } catch {
        return [String]()
    }
    return matches

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

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.

Upvotes: 10

Related Questions