Created
August 13, 2015 20:27
-
-
Save jkopelioff/626216bf982723325224 to your computer and use it in GitHub Desktop.
Additional functionality to Strings using regex
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
| extension String { | |
| func matchRegex(pattern: Regex) -> Bool { | |
| let range: NSRange = NSMakeRange(0, count(self)) | |
| if pattern.regex != nil { | |
| let matches: [AnyObject] = pattern.regex!.matchesInString(self, options: pattern.matchingOptions, range: range) | |
| return matches.count > 0 | |
| } | |
| return false | |
| } | |
| func match(patternString: String) -> Bool { | |
| return self.matchRegex(Regex(pattern: patternString)) | |
| } | |
| func replaceRegex(pattern: Regex, template: String) -> String { | |
| if self.matchRegex(pattern) { | |
| let range: NSRange = NSMakeRange(0, count(self)) | |
| if pattern.regex != nil { | |
| return pattern.regex!.stringByReplacingMatchesInString(self, options: pattern.matchingOptions, range: range, withTemplate: template) | |
| } | |
| } | |
| return self | |
| } | |
| func replace(pattern: String, template: String) -> String { | |
| return self.replaceRegex(Regex(pattern: pattern), template: template) | |
| } | |
| func captureUsingRegex(pattern:String) -> [[String]] | |
| { | |
| var error:NSError? | |
| var regex:NSRegularExpression = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive, error: &error)! | |
| var matches:[NSTextCheckingResult] = regex.matchesInString(self, options: nil, range: NSMakeRange(0, count(self))) as! [NSTextCheckingResult] | |
| var retMatches = [[String]]() | |
| for match in matches { | |
| var strings:[String] = [String]() | |
| for (var i = 0; i < match.numberOfRanges; i++) { | |
| let range = match.rangeAtIndex(i) | |
| strings.append((self as NSString).substringWithRange(range)) | |
| } | |
| retMatches.append(strings) | |
| } | |
| return retMatches | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment