Created
June 11, 2014 11:01
-
-
Save frozzare/e2f58b897ed74c8478ae to your computer and use it in GitHub Desktop.
Regex example
This file contains hidden or 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 | |
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"] |
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
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.