如何快速找到NSTextCheckingResult对象的子字符串?

Dev*_*ian 3 swift2

我想知道如何从NSTextCheckingResult对象中找到子字符串。到目前为止,我已经尝试过了:

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?
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ann 5

尝试这个:

import Foundation

let input = "My name Swift is Taylor Swift "// the input string where we will find for the pattern
let nsString = input as NSString

let regex = try NSRegularExpression(pattern: "Swift|Taylor", options: NSRegularExpressionOptions.CaseInsensitive)
//matches will store the all range objects in form of NSTextCheckingResult 
let matches = regex.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count)) as Array<NSTextCheckingResult>

for match in matches {
    // what will be the code
    let range = match.range
    let matchString = nsString.substringWithRange(match.range) as String
    print("match is \(range) \(matchString)")
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*nil 5

这是适用于 Swift 3 的代码。它返回 String 数组

    results.map {
        String(text[Range($0.range, in: text)!])
    }
Run Code Online (Sandbox Code Playgroud)

所以总体示例可能是这样的:

    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)!])
    }
Run Code Online (Sandbox Code Playgroud)