简体   繁体   English

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

[英]Extracting address elements from a String using NSDataDetector in Swift 3.0

I'm attempting to use NSDataDetector to addresses from a string. 我正在尝试使用NSDataDetector来处理字符串。 I've taken a look at NSHipster's article on NSDataDetector as well as Apple's NSDataDetector documentation . 我已经看到了在NSHipster对第NSDataDetector以及苹果的NSDataDetector文档 I've got the following method to the point where it'll pull addresses out of a string: 我有以下方法,它将从字符串中提取地址:

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
}

I'd like to pull out elements of addresses, not the entire address. 我想提取地址的元素,而不是整个地址。 In NSHipster's NSDataDetector post in the Data Detector Match Types section, I see address components such as NSTextCheckingCityKey , NSTextCheckingStateKey , and NSTextCheckingZIPKey . 数据检测器匹配类型部分的NSHipster的NSDataDetector帖子中,我看到地址组件,如NSTextCheckingCityKeyNSTextCheckingStateKeyNSTextCheckingZIPKey I'm unable to use those keys in the NSDataDetector 's initialization. 我无法在NSDataDetector的初始化中使用这些键。

I dug around on GitHub to see if I could find an example to crib from, but the only stuff I'm able to find is Objective-C code or declarative stuff in the master Swift repo. 我在GitHub上挖了一下,看看我是否能找到一个来自crib的例子,但我能找到的唯一东西是主Swift repo中的Objective-C代码或声明性东西。

I'm 99% sure I can pull out the individual components of an address, but I'm too dumb to figure it out. 我99%肯定我可以拿出一个地址的各个组成部分,但我太笨了,无法弄明白。 Thank you for reading. 谢谢你的阅读。 I welcome suggestions. 我欢迎建议。

I haven't used this class before, but it looks like it returns objects of type NSTextCheckingResult . 我之前没有使用过这个类,但它看起来像是返回NSTextCheckingResult类型的NSTextCheckingResult If you get a result of type NSTextCheckingTypeAddress then you can ask the result for it's addressComponents , which will be a dictionary containing the different parts of the address. 如果您得到NSTextCheckingTypeAddress类型的结果,那么您可以向结果询问它的addressComponents ,它将是包含地址不同部分的字典。

EDIT: 编辑:

Here is some working playground code I just banged out: 这是我刚刚敲定的一些工作游乐场代码:

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
}

This code prints: 此代码打印:

matched 2 addresses 匹配2个地址

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

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

You can easily extract all addresses, URLs and phone numbers using NSDataDetector. 您可以使用NSDataDetector轻松提取所有地址,URL和电话号码。

Swift 4.2 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")
 }

For address use only 仅供地址使用

let detectorType: NSTextCheckingResult.CheckingType = [.address]

Credits: http://www.swiftdevcenter.com/how-to-detect-url-address-phone-number-and-dates-using-nsdatadetector/ 致谢: http//www.swiftdevcenter.com/how-to-detect-url-address-phone-number-and-dates-using-nsdatadetector/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM