我想知道如何从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)
尝试这个:
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)
这是适用于 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)
| 归档时间: |
|
| 查看次数: |
4184 次 |
| 最近记录: |