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

时间:2016-12-10 15:34:13

标签: ios regex swift swift3 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's article on NSDataDetector以及Apple's NSDataDetector documentation。我已经得到了以下方法,以便从字符串中提取地址:

NSDataDetector

我想提取地址元素,而不是整个地址。在数据检测器匹配类型部分的NSHipster's NSDataDetector post中,我看到了NSTextCheckingCityKeyNSTextCheckingStateKeyNSTextCheckingZIPKey等地址组件。我无法在Sub Import() ' ' Import Macro ' ' Keyboard Shortcut: Ctrl+Shift+I ' Application.ScreenUpdating = False Dim copySheet As Worksheet Dim pasteSheet As Worksheet Set copySheet = Worksheets("Sheet3") Set pasteSheet = Worksheets("Sheet2") copySheet.Range("B7:R7").Copy With pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) .PasteSpecial xlPasteValues .PasteSpecial xlPasteFormats Application.CutCopyMode = False Application.ScreenUpdating = True End With End Sub 的初始化中使用这些密钥。

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

我99%确定我可以提取地址的各个组成部分,但我太愚蠢了。谢谢你的阅读。我欢迎提出建议。

2 个答案:

答案 0 :(得分:7)

我之前没有使用过这个类,但它看起来像是返回 WebServiceHelper.postWebServiceCall(Constants.BaseURL, params: aParams as [String : AnyObject]?, isShowLoader: true, success: { (responceObj) in if "\(responceObj["RespCode"])" != "1" { let alert = UIAlertController(title: Constants.kAppName, message: "\(responceObj["RespMsg"])", preferredStyle: UIAlertControllerStyle.alert) let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in } alert.addAction(OKAction) self.present(alert, animated: true, completion: nil) } else { let aParams : [String : String] = [ "Password" : self.dictAddLogin[AddLoginConstants.kPassword]!, ] CommonMethods.saveCustomObject(aParams as AnyObject?, key: Constants.kLoginData) } }, failure: { (error) in CommonMethods.showAlertWithError(Constants.kALERT_TITLE_Error, strMessage: error.localizedDescription,withTarget: (AppDelegate.getDelegate().window!.rootViewController)!) }) } 类型的对象。如果您得到NSTextCheckingResult类型的结果,那么您可以询问结果NSTextCheckingTypeAddress,这将是包含地址不同部分的字典。

编辑:

这是我刚刚敲定的一些工作游乐场代码:

addressComponents

此代码打印:

  

匹配2个地址

     

地址dict = [" Street":" 123 Elm Street"," ZIP":" 45404"," City& #34;:" Daton"," State":" OH"]。       City =" Daton"

     

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

答案 1 :(得分:1)

您可以使用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-number-and-dates-using-nsdatadetector/