我正在尝试使用NSDataDetector
字符串中的地址。我查看了NSHipster 的文章NSDataDetector
以及Apple 的 NSDataDetector 文档。我有以下方法可以从字符串中提取地址:
func getAddress(from dataString: String) -> [String] {
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.address.rawValue)
let matches = detector.matches(in: dataString, options: [], range: NSRange(location: 0, length: dataString.utf16.count))
var addressArray = [String]()
// put matches into array of Strings
for match in matches {
let address = (dataString as NSString).substring(with: match.range)
addressArray.append(address)
}
return addressArray
}
我想提取地址元素,而不是整个地址。在NSHipster 的NSDataDetector
数据检测器匹配类型部分的帖子中,我看到了诸如NSTextCheckingCityKey
、NSTextCheckingStateKey
和NSTextCheckingZIPKey
. 我无法在NSDataDetector
的初始化中使用这些键。
我在 GitHub 上四处寻找,看看是否可以找到一个示例,但我能找到的唯一东西是 Objective-C 代码或主 Swift 存储库中的声明性内容。
我 99% 确信我可以提取地址的各个组成部分,但我太笨了,无法弄清楚。感谢您的阅读。我欢迎建议。