Skip to content

Instantly share code, notes, and snippets.

@mattt
Created August 11, 2014 18:08
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mattt/2099ee21bbfbebaa94a3 to your computer and use it in GitHub Desktop.
Save mattt/2099ee21bbfbebaa94a3 to your computer and use it in GitHub Desktop.
Creating a regular expression object from a String literal
class Regex {
let pattern: String
let options: NSRegularExpressionOptions!
private var matcher: NSRegularExpression {
return NSRegularExpression(pattern: self.pattern, options: nil, error: nil)
}
required 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
}
}
extension Regex: StringLiteralConvertible, ExtendedGraphemeClusterLiteralConvertible {
typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
class func convertFromExtendedGraphemeClusterLiteral(value: ExtendedGraphemeClusterLiteralType) -> Self {
return self(pattern: value)
}
class func convertFromStringLiteral(value: StringLiteralType) -> Self {
return self(pattern: value)
}
}
// MARK: -
protocol RegularExpressionMatchable {
func match(regex: Regex) -> Bool
}
infix operator =~ { associativity left precedence 130 }
func =~<T: RegularExpressionMatchable> (left: T, right: Regex) -> Bool {
return left.match(right)
}
extension String: RegularExpressionMatchable {
func match(regex: Regex) -> Bool {
return regex.match(self)
}
}
"foo" =~ "f" // true
@winzig
Copy link

winzig commented Aug 12, 2014

Awesome! Why isn't this part of Swift? ;-)

@neilpa
Copy link

neilpa commented Aug 12, 2014

I'm assuming you intended to pass self.options to the NSRegularExpression c'tor when creating the matcher.

@feinstimmer
Copy link

Thank you! Great! Your code was working in my project until i (to bad) updated to Xcode 6.1, now i am getting 3 errors in extension Regex: Type 'Regex' does not confirm to protocol 'StringLiteralConvertible'; to protocol 'Unicode ScalarLiteralConvertible'; to protocol 'ExtendedGraphemeClusterLiteralConvertible'.

@grosch
Copy link

grosch commented Nov 26, 2014

I've taken this and updated it for the current version of Xcode, and also made it so you can use an actual NSRegularExpression as the RHS. See https://gist.github.com/grosch/d3daeec1eefcf1614442

@davidfuzju
Copy link

@ded
Copy link

ded commented Jun 30, 2015

thank you for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment