Created
November 4, 2014 21:48
-
-
Save inre/7c93405e43e75f4dae0e to your computer and use it in GitHub Desktop.
Replace with regular expression
This file contains 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
import Foundation | |
struct Regex { | |
let pattern: String | |
let options: NSRegularExpressionOptions! | |
private var matcher: NSRegularExpression { | |
return NSRegularExpression(pattern: self.pattern, options: self.options, error: nil)! | |
} | |
init(pattern: String, options: NSRegularExpressionOptions = nil) { | |
self.pattern = pattern | |
self.options = options | |
} | |
func match(string: String, options: NSMatchingOptions = nil) -> Bool { | |
return self.matcher.numberOfMatchesInString(string, options: options, range: NSMakeRange(0, string.utf16Count)) != 0 | |
} | |
func replace(string: String, withString: String) -> String { | |
return string.stringByReplacingOccurrencesOfString(self.pattern, withString: withString, options: NSStringCompareOptions.RegularExpressionSearch, range: nil) | |
} | |
} | |
protocol RegularExpressionMatchable { | |
func match(regex: Regex) -> Bool | |
} | |
extension String: RegularExpressionMatchable { | |
func match(regex: Regex) -> Bool { | |
return regex.match(self) | |
} | |
} | |
func ~=<T: RegularExpressionMatchable>(pattern: Regex, matchable: T) -> Bool { | |
return matchable.match(pattern) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment