使用Swift 3.0中的NSDataDetector从String中提取地址元素

Adr*_*ian 6 regex ios nsdatadetector swift swift3

我正在尝试使用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
}
Run Code Online (Sandbox Code Playgroud)

我想提取地址的元素,而不是整个地址.在NSHipster的NSDataDetector帖子数据检测器的匹配类型中,我看到的地址组件,如NSTextCheckingCityKey,NSTextCheckingStateKeyNSTextCheckingZIPKey.我无法在NSDataDetector初始化中使用这些键.

我在GitHub上挖了一下,看看我是否能找到一个来自crib的例子,但我能找到的唯一东西是主Swift回购中的Objective-C代码或声明性东西.

我99%肯定我可以拿出一个地址的各个组成部分,但我太愚蠢了,无法弄明白.谢谢你的阅读.我欢迎建议.

Dun*_*n C 8

我之前没有使用过这个类,但看起来它返回了类型的对象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
}
Run Code Online (Sandbox Code Playgroud)

此代码打印:

匹配2个地址

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

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