Last active
September 24, 2015 20:59
-
-
Save evgeniyd/76948bb16c5db3ac0ef0 to your computer and use it in GitHub Desktop.
NSRegularExpression w/ Swift 2.0; Two cases: 1) w/ catch-all” block 2) w/ "forced-try"
This file contains 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
var input: String | |
// CASE 1 | |
func validateWithError(error: NSErrorPointer) -> Bool { | |
var regexpError: NSError? | |
let regexp: NSRegularExpression? | |
do { | |
regexp = try NSRegularExpression(pattern: "[a-zA-Z0-9_]{4,}", options:[]) | |
} catch let error as NSError { | |
regexpError = error | |
regexp = nil | |
} | |
if regexp != nil { | |
// validation | |
let inputRange = NSRange(location:0, length: nonEmptyInput.characters.count ) | |
let result = regexp!.rangeOfFirstMatchInString(nonEmptyInput, options: .Anchored, range: inputRange) | |
if result.location == NSNotFound { | |
return false | |
} | |
else { | |
return true | |
} | |
} | |
else { | |
// regexp was not initialized | |
if error != nil { error.memory = regexpError } | |
return false | |
} | |
} | |
// CASE 2 | |
func validateWithError(error: NSErrorPointer) -> Bool { | |
let regexp = try! NSRegularExpression(pattern: "[a-zA-Z0-9_]{4,}", options: []) | |
let inputRange = NSRange(location:0, length: nonEmptyInput.characters.count ) | |
let result = regexp.rangeOfFirstMatchInString(nonEmptyInput, options: .Anchored, range: inputRange) | |
if result.location == NSNotFound { | |
// regexp validation failed | |
// TODO: create error object for it | |
return false | |
} | |
else { | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment