Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Regex matches
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)")
}
}
@NathanFlurry
Copy link

NathanFlurry commented Jul 9, 2014

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 "..").

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