Skip to content

Instantly share code, notes, and snippets.

@xNekOIx
Forked from mattt/regex.swift
Last active August 29, 2015 14:12
Show Gist options
  • Save xNekOIx/92080a6079057d75972d to your computer and use it in GitHub Desktop.
Save xNekOIx/92080a6079057d75972d to your computer and use it in GitHub Desktop.
Swift String literal regular expression + switch pattern match operator
//
// Mattt's example from NSHipster updated for 8.1 API. (NSHipster article http://nshipster.com/swift-literal-convertible/ )
// Additions for pattern matching for use in switch statements taken from http://lesstroud.com/swift-using-regex-in-switch-statements/
//
// -------
// xNekOIx
//
import Foundation
/// Class representing ICU regular expression for use as StringLiteralConvertible
public final class Regex {
let pattern: String
let options: NSRegularExpressionOptions!
/**
Default initializer
:param: pattern The regular expression to compile of String type
:param: options The regular expression options that are applied to the expression during matching. Default value is nil.
:returns: An instance of Regex class
*/
public required init(pattern: String, options: NSRegularExpressionOptions = nil) {
self.pattern = pattern
self.options = options
}
var matcher: NSRegularExpression {
// TODO: do something with error and optional
var error: NSError? = nil
let regex = NSRegularExpression(pattern: self.pattern, options: nil, error: &error)!
return regex
}
func match(string: String, options: NSMatchingOptions = nil) -> Bool {
return self.matcher.numberOfMatchesInString(string, options: options, range: NSMakeRange(0, string.utf16Count)) != 0
}
}
extension Regex: StringLiteralConvertible {
public typealias UnicodeScalarLiteralType = StringLiteralType
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public convenience init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(pattern: value)
}
public convenience init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(pattern: value)
}
public convenience init(stringLiteral value: StringLiteralType) {
self.init(pattern: value)
}
}
// MARK: -
public protocol RegularExpressionMatchable {
func match(regex: Regex) -> Bool
}
/// Operator for String matching String on the left side to the Regex (String representation of the regex pattern) on the right side
infix operator =~ { associativity left precedence 130 }
public func =~<T: RegularExpressionMatchable> (left: T, right: Regex) -> Bool {
return left.match(right)
}
/// Switch pattern match operator for Regex instances
public func ~=<T: RegularExpressionMatchable>(pattern: Regex, matchable: T) -> Bool {
return matchable.match(pattern)
}
extension String: RegularExpressionMatchable {
public func match(regex: Regex) -> Bool {
return regex.match(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment