swift2 如何在swift中从NSTextCheckingResult对象中找到子字符串?

oiopk7p5  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(247)

我想知道如何从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?
}
xienkqul

xienkqul1#

试试看:

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)")
}
ymdaylpp

ymdaylpp2#

下面是Swift 3的代码。它返回一个String数组

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

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

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)!])
    }
wqsoz72f

wqsoz72f3#

你可以把这段代码放在for循环中,str将包含匹配的字符串。
let range = match.range let str = (input as NSString).substringWithRange(range)

相关问题