How can I find the substrings from the NSTextCheckingResult objects in swift?

Viewed 8175

I wonder how it is possible to find substrings from a NSTextCheckingResult object. I have tried this so far:

import Foundation {
    let input = "My name Swift is Taylor Swift "
    let regex = try NSRegularExpression(pattern: "Swift|Taylor", options:NSRegularExpressionOptions.CaseInsensitive) 
    let matches = regex.matchesInString(input, options: [], range:   NSMakeRange(0, input.characters.count))
    for match in matches {
    // what will be the code here?
}
3 Answers

Here is code that works for Swift 3. It returns array of String

    results.map {
        String(text[Range($0.range, in: text)!])
    }

So overall example could be like this:

    let regex = try NSRegularExpression(pattern: regex)
    let results = regex.matches(in: text,
                                range: NSRange(text.startIndex..., in: text))
    return results.map {
        String(text[Range($0.range, in: text)!])
    }
Related