6

我正在尝试使用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数据检测器匹配类型部分的帖子中,我看到了诸如NSTextCheckingCityKeyNSTextCheckingStateKeyNSTextCheckingZIPKey. 我无法在NSDataDetector的初始化中使用这些键。

我在 GitHub 上四处寻找,看看是否可以找到一个示例,但我能找到的唯一东西是 Objective-C 代码或主 Swift 存储库中的声明性内容。

我 99% 确信我可以提取地址的各个组成部分,但我太笨了,无法弄清楚。感谢您的阅读。我欢迎建议。

4

2 回答 2

9

我以前没有使用过这个类,但看起来它返回了 type 的对象NSTextCheckingResult。如果你得到一个类型的结果,NSTextCheckingTypeAddress那么你可以询问它的结果addressComponents,这将是一个包含地址不同部分的字典。

编辑:

这是我刚刚敲出的一些工作操场代码:

import UIKit

var string = "Now is the time for all good programmers to babble incoherently.\n" +
"Now is the time for all good programmers to babble incoherently.\n" +
"Now is the time for all good programmers to babble incoherently.\n" +
"123 Elm Street\n" +
"Daton, OH 45404\n" +
"Now is the time for all good programmers to babble incoherently.\n" +
"2152 E Street NE\n" +
"Washington, DC 20001"

let results = getAddress(from: string)

print("matched \(results.count) addresses")
for result in results {
  let city = result[NSTextCheckingCityKey] ?? ""
  print("address dict = \(result).")
  print("    City = \"\(city)\"")
}

func getAddress(from dataString: String) -> [[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 resultsArray =  [[String: String]]()
  // put matches into array of Strings
  for match in matches {
    if match.resultType == .address,
      let components = match.addressComponents {
      resultsArray.append(components)
    } else {
      print("no components found")
    }
  }
  return resultsArray
}

此代码打印:

匹配 2 个地址

地址字典 = [“街道”:“榆树街 123 号”,“邮编”:“45404”,“城市”:“达顿”,“州”:“哦”]。城市 = “达顿”

地址 dict = [“Street”:“2152 E Street NE”,“ZIP”:“20001”,“City”:“Washington”,“State”:“DC”]。城市 = “华盛顿”

于 2016-12-10T15:52:59.230 回答
2

您可以使用 NSDataDetector 轻松提取所有地址、URL 和电话号码。

斯威夫特 4.2

let string = "This is an address PO Box 7775, San Francisco, CA. This is a url 
http:/
www.swiftdevcenter.com/. This is second url: https://www.google.com/. This is 
mobile number
+18987656789. This is a date 01/26/2019"
let detectorType: NSTextCheckingResult.CheckingType = [.address, .phoneNumber, 
.link, .date]

do {
   let detector = try NSDataDetector(types: detectorType.rawValue)
   let results = detector.matches(in: string, options: [], range: 
   NSRange(location: 0, length: string.utf16.count))

   for result in results {
     if let range = Range(result.range, in: string) {
         let matchResult = string[range]
         print("result: \(matchResult), range: \(result.range)")
     }
   }

 } catch {
    print("handle error")
 }

仅供地址使用

let detectorType: NSTextCheckingResult.CheckingType = [.address]

学分:http ://www.swiftdevcenter.com/how-to-detect-url-address-phone-number-and-dates-using-nsdatadetector/

于 2019-01-26T08:17:14.383 回答