使用Swift 3.0中的NSDATADETECTOR从字符串中提取地址元素



我正在尝试使用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上挖出来,看看我是否可以找到CRIB的示例,但是我唯一能找到的是Objective-C代码或大师Swift Repo中的声明性内容。

我确定我可以拿出一个地址的各个组件,但是我太愚蠢了,无法弄清楚。谢谢您的阅读。我欢迎建议。

我以前从未使用过此类,但是看起来它返回类型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 Streetn" +
"Daton, OH 45404n" +
"Now is the time for all good programmers to babble incoherently.n" +
"2152 E Street NEn" +
"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个地址

地址dict = ["街":" 123 Elm Street"," Zip":" 45404"," City":" Daton"," state":" oh"]。 城市=" daton"

地址dict = ["街":" 2152 E Street NE"," Zip":" 20001"," City":" Washington"," state":" DC"]。 城市="华盛顿"

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

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-phone-number-and-number-and-dates-using-sus-using-nsdatadetector/

最新更新