Skip to content

Instantly share code, notes, and snippets.

@takafumir
Last active June 16, 2016 02:43
Show Gist options
  • Save takafumir/317b9325bebf677326b4 to your computer and use it in GitHub Desktop.
Save takafumir/317b9325bebf677326b4 to your computer and use it in GitHub Desktop.
Swift utility class for regular expression
import Foundation
class Regexp {
let internalRegexp: NSRegularExpression
let pattern: String
init(_ pattern: String) {
self.pattern = pattern
var error: NSError?
self.internalRegexp = NSRegularExpression( pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive, error: &error)!
}
func isMatch(input: String) -> Bool {
let matches = self.internalRegexp.matchesInString( input, options: nil, range:NSMakeRange(0, count(input)) )
return matches.count > 0
}
func matches(input: String) -> [String]? {
if self.isMatch(input) {
let matches = self.internalRegexp.matchesInString( input, options: nil, range:NSMakeRange(0, count(input)) )
var results: [String] = []
for i in 0 ..< matches.count {
results.append( (input as NSString).substringWithRange(matches[i].range) )
}
return results
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment