Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to get URL in string swift with Capitalized symbols

Tags:

regex

ios

swift

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.

like image 481
nabiullinas Avatar asked Jun 23 '15 08:06

nabiullinas


People also ask

What is a good regex to match a URL?

@:%_\+~#= , to match the domain/sub domain name.

What is URL regex?

URL Regular Expession tutorial. Regular expressions are a combination of characters that are used to define a search pattern. They are often used in search engines and text editors and they can look daunting the first time you encounter one. Or maybe even the second or third time too.

Does Swift have regex?

Swift's regex syntax is compatible with Perl, Python, Ruby, Java, NSRegularExpression, and many, many others. This regex matches one or more digits. The compiler knows regex syntax, so you'll get syntax highlighting, compile-time errors, and even strongly-typed captures, which we'll be meeting later.

What is regex in iOS?

A regex ( also known as regular expressions) is a pattern string. These pattern strings allow you to search specific patterns in documents and to validate email, phone number etc. In iOS and MacOS regex been handled by NSRegularExpression .


2 Answers

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.

like image 162
Wiktor Stribiżew Avatar answered Oct 27 '22 00:10

Wiktor Stribiżew


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
like image 40
alegelos Avatar answered Oct 27 '22 00:10

alegelos