nabiullinas nabiullinas - 6 months ago 159
iOS Question

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.

Answer

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.

Comments