Skip to content

Instantly share code, notes, and snippets.

@frozzare
Created June 11, 2014 11:01
Show Gist options
  • Save frozzare/e2f58b897ed74c8478ae to your computer and use it in GitHub Desktop.
Save frozzare/e2f58b897ed74c8478ae to your computer and use it in GitHub Desktop.
Regex example
import Foundation
extension String {
func exec (str: String) -> Array<String> {
var err : NSError?
let regex = NSRegularExpression(pattern: self, options: NSRegularExpressionOptions(0), error: &err)
if err {
return Array<String>()
}
let nsstr = str as NSString
let all = NSRange(location: 0, length: nsstr.length)
var matches : Array<String> = Array<String>()
regex.enumerateMatchesInString(str, options: NSMatchingOptions(0), range: all) {
(result : NSTextCheckingResult!, _, _) in
matches.append(nsstr.substringWithRange(result.range))
}
return matches
}
}
let res = "\\w+".exec("Hello world")
println(res) // ["Hello", "world"]
@yuhua-chen
Copy link

This is an elegant solution!! Thanks a lot

@wiesys
Copy link

wiesys commented Oct 27, 2014

Great idea! Thanks!

@zgmorris13
Copy link

This no longer works in swift 2.0. I've tried messing with it, but I keep getting the error saying that the arguments don't work.

@dbrownstone
Copy link

The following works in Swift 2.0:

func exec (str: String) -> Array<String> {
    do {
        let regex = try NSRegularExpression(pattern: self, options: NSRegularExpressionOptions(rawValue: 0))
        let nsstr = str as NSString
        let all = NSRange(location: 0, length: nsstr.length)
        var matches : Array<String> = Array<String>()
        regex.enumerateMatchesInString(str, options: NSMatchingOptions(rawValue: 0), range: all) {
            (result : NSTextCheckingResult?, _, _) in
            let theResult = nsstr.substringWithRange(result!.range)
            matches.append(theResult)
        }
        return matches
    } catch {
        return Array<String>()
    }
}

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