苹果提供了一个方法,可以从一大串字符串中提取出有意义的字符串,比如URL,日期,地址等
let detector = try? NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingAllTypes))
let inputText = inoutText.string
var resultString = ""
if let matches = detector?.matchesInString(inputText!, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, (inputText! as NSString).length)) {
for match in matches {
let result = match
switch result.resultType {
case NSTextCheckingType.Link:
resultString += "Link: \(result.URL)\n"
case NSTextCheckingType.Date:
resultString += "Date: \(result.date)\n"
case NSTextCheckingType.PhoneNumber:
resultString += "Date: \(result.phoneNumber)\n"
case NSTextCheckingType.Address:
resultString += "Date: \(result.addressComponents)\n"
default:
resultString += "Other: \(result.description)\n"
}
}
}
print(resultString)
outputText.stringValue = resultString