Last active
May 20, 2020 20:52
-
-
Save haikieu/2bae386a9a17dbbd6cc7c91b920804f0 to your computer and use it in GitHub Desktop.
Simple Regular Expression Search Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func search(pattern: String, input text: String) -> [NSTextCheckingResult] { | |
guard let regex = try? NSRegularExpression.init(pattern: pattern, options: .caseInsensitive) else { | |
return [] | |
} | |
return regex.matches(in: text, options: [], range: NSRange.init(location: 0, length: text.count)) | |
} | |
func searchStrings(pattern: String, input text: String) -> [String] { | |
return search(pattern: pattern, input: text).map { (text as NSString).substring(with:$0.range) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment