Regular expression to get url in swift string with capital letters

I am trying to get the urls in the text. So, earlier I used this expression:

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

But I had a problem when the user entered URLs with uppercase characters (for example, Http://Google.com , it does not match it).

I tried:

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

But nothing happened.

+9
source share
4 answers

You will disable case sensitivity with the built-in i flag in the regular expression, see Foundation Framework Reference for more information on the available regular expression functions.

(?ismwx-ismwx)
Flag settings. Change the flag settings. Changes apply to part of the template after installation. For example, (? I) is changed to case insensitive. Flags are defined in flag options.

For readers:

URL matching in larger texts is already a problem, but for this case a simple regular expression like

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

will do what the OP requires to match only URLs starting with http or https or https etc.

+8
source

Swift 4

1- Create a line 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 that

 "www.google.com".isValidURL() 
+3
source

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 
+1
source

Make line extension

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

call using this

 "www.testsite.edu".isAlphanumeric // true "flsd.testsite.com".isAlphanumeric //false 
+1
source

Source: https://habr.com/ru/post/989587/


All Articles