在 Swift 3.0 中使用 NSDataDetector 从字符串中提取地址元素

Extracting address elements from a String using NSDataDetector in Swift 3.0

我正在尝试使用 NSDataDetector 来处理字符串中的地址。我看过 NSHipster's article on NSDataDetector as well as Apple's NSDataDetector documentation。我有以下方法可以从字符串中提取地址:

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's NSDataDetector post in the Data Detector Match Types section, I see address components such as NSTextCheckingCityKey, NSTextCheckingStateKey, and NSTextCheckingZIPKey。我无法在 NSDataDetector 的初始化中使用这些键。

我在 GitHub 上四处寻找,看看是否可以找到一个例子来借鉴,但我唯一能找到的东西是 Objective-C 代码或 master [中的声明性东西] =31=]回购。

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

我以前没用过这个 class,但它看起来像 returns 类型 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
}

此代码打印:

matched 2 addresses

address dict = ["Street": "123 Elm Street", "ZIP": "45404", "City": "Daton", "State": "OH"]. City = "Daton"

address dict = ["Street": "2152 E Street NE", "ZIP": "20001", "City": "Washington", "State": "DC"]. City = "Washington"

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

Swift 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/