Skip to content

Instantly share code, notes, and snippets.

@SamRothCA
Forked from ningsuhen/Regex.swift
Created December 27, 2015 17:04
Show Gist options
  • Save SamRothCA/a87ab08fabed134a07d8 to your computer and use it in GitHub Desktop.
Save SamRothCA/a87ab08fabed134a07d8 to your computer and use it in GitHub Desktop.
Swift extension for Native String class to support Regex match and Regex replace. Credit - http://www.swift-studies.com/blog/2014/6/12/regex-matching-and-template-replacement-operators-in-swift
import Foundation
struct Regex: StringLiteralConvertible {
var pattern: String {
didSet {
updateRegex()
}
}
var expressionOptions: NSRegularExpressionOptions {
didSet {
updateRegex()
}
}
var matchingOptions: NSMatchingOptions
var regex: NSRegularExpression?
init(pattern: String,
expressionOptions: NSRegularExpressionOptions = NSRegularExpressionOptions(),
matchingOptions: NSMatchingOptions = NSMatchingOptions()
) {
self.pattern = pattern
self.expressionOptions = expressionOptions
self.matchingOptions = matchingOptions
updateRegex()
}
mutating func updateRegex() {
regex = try? NSRegularExpression(pattern: pattern, options: expressionOptions)
}
init(stringLiteral: String) {
self.init(pattern: stringLiteral)
}
init(extendedGraphemeClusterLiteral: String) {
self.init(pattern: extendedGraphemeClusterLiteral)
}
init(unicodeScalarLiteral: String) {
self.init(pattern: unicodeScalarLiteral)
}
}
extension String {
func matchRegex(pattern: Regex) -> Bool {
let range = NSRange(location: 0, length: characters.startIndex.distanceTo(endIndex))
guard let regex = pattern.regex else { return false }
return !regex.matchesInString(self, options: pattern.matchingOptions, range: range).isEmpty
}
func match(patternString: String) -> Bool {
return self.matchRegex(Regex(pattern: patternString))
}
func replaceRegex(pattern: Regex, template: String) -> String {
guard matchRegex(pattern), let regex = pattern.regex else { return self }
let range = NSRange(location: 0, length: characters.startIndex.distanceTo(endIndex))
return regex.stringByReplacingMatchesInString(self, options: pattern.matchingOptions, range: range, withTemplate: template)
}
func replace(pattern: String, template: String) -> String {
return self.replaceRegex(Regex(pattern: pattern), template: template)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment