Last active
January 27, 2016 19:11
-
-
Save KingOfBrian/8d2c6d85cb4079aabde6 to your computer and use it in GitHub Desktop.
Swift Regex matches
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
import Foundation | |
operator infix =~ {} | |
func =~ (input: String, pattern: String) -> String[]? { | |
let regex = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: nil) | |
let results = regex.matchesInString(input, | |
options: nil, | |
range: NSMakeRange(0, countElements(input)) | |
)! as NSTextCheckingResult[] | |
if (results.count > 0) { | |
var values:Array<String> = [] | |
for result in results { | |
for i in 0..result.numberOfRanges { | |
let range = result.rangeAtIndex(i) | |
values += input | |
.substringFromIndex(range.location) | |
.substringToIndex(range.length) | |
} | |
} | |
return values | |
} else { | |
return nil | |
} | |
} | |
if let matches = "123alksdjfladskfj3234" =~ "(\\d+)a" { | |
for value in matches { | |
println("Found \(value)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! By the way, just to let you know, you should update it to the new array syntax (I.e. [String], not String[] and "..<" not "..").