Regular expression to get URL in string swift with

2020-08-25 04:08发布

问题:

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.

回答1:

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.



回答2:

Swift 4

1- Create String extension

2- Use it

import Foundation
extension String {

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

Use it like this

"www.google.com".isValidURL()


回答3:

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


回答4:

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


标签: ios regex swift