Skip to content

Instantly share code, notes, and snippets.

@dr-skot
Forked from ningsuhen/Regex.swift
Last active March 9, 2016 13:02
Show Gist options
  • Save dr-skot/71fcba4debd9c6ebcba3 to your computer and use it in GitHub Desktop.
Save dr-skot/71fcba4debd9c6ebcba3 to your computer and use it in GitHub Desktop.
Swift extension that adds convenient regex methods to String. Forked from ningsuhen & cleaned up for Swift 2.0
import Foundation
struct Regex {
var pattern: String {
didSet { updateRegex() }
}
var expressionOptions: NSRegularExpressionOptions {
didSet { updateRegex() }
}
var matchingOptions: NSMatchingOptions
var regex: NSRegularExpression?
init(pattern: String, expressionOptions: NSRegularExpressionOptions, matchingOptions: NSMatchingOptions) {
self.pattern = pattern
self.expressionOptions = expressionOptions
self.matchingOptions = matchingOptions
updateRegex()
}
init(pattern: String) {
self.init(pattern: pattern, expressionOptions: [], matchingOptions: [])
}
mutating func updateRegex() {
regex = try? NSRegularExpression(pattern: pattern, options: expressionOptions)
}
}
extension String {
func getMatches(pattern: Regex) -> [NSTextCheckingResult] {
guard let regex = pattern.regex else { return [] }
let range: NSRange = NSMakeRange(0, characters.count)
return regex.matchesInString(self, options: pattern.matchingOptions, range: range)
}
func getMatches(pattern: String) -> [NSTextCheckingResult] {
return getMatches(Regex(pattern: pattern))
}
func match(pattern: Regex) -> Bool {
return !getMatches(pattern).isEmpty
}
func match(patternString: String) -> Bool {
return self.match(Regex(pattern: patternString))
}
func replace(pattern: Regex, with template: String) -> String {
guard let regex = pattern.regex else { return self }
let range: NSRange = NSMakeRange(0, characters.count)
return regex.stringByReplacingMatchesInString(self, options: pattern.matchingOptions, range: range, withTemplate: template)
}
func replace(pattern: String, with template: String) -> String {
return self.replace(Regex(pattern: pattern), with: template)
}
}
/*
//e.g. replaces symbols +, -, space, ( & ) from phone numbers
"+91-999-929-5395".replace("[-\\s\\(\\)]", template: "")
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment