检查字符串中是否存在电话号码

时间:2017-05-18 08:23:21

标签: ios swift xcode string

嘿,我想检查UITextView(可能是否相关)是否包含文本中的电话号码。我正在使用Swift 2.3,但是如果你在Swift 3中找到它,我会尝试翻译它。

例如,这些输入应该起作用:

  • "早上好,627137152"
  • "早上好,+ 34627217154"
  • "早上好,627 11 71 54"

最后一种情况,如果其他工作很容易,只需更换" "发生在""并检查上一个函数containsPhone。

我尝试过这个解决方案,但不适用于第一种情况:(Find phone number in string - regular

谢谢。

4 个答案:

答案 0 :(得分:11)

NSDataDetector提供了一种方便的方法:

let string = "Good morning, 627137152 \n Good morning, +34627217154 \n Good morning, 627 11 71 54"

do {
   let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
   let numberOfMatches = detector.numberOfMatches(in: string, range: NSRange(string.startIndex..., in: string))
   print(numberOfMatches) // 3
} catch {
   print(error)
}

或者如果你想提取数字

let matches = detector.matches(in: string, range: NSRange(string.startIndex..., in: string))

for match in matches{
    if match.resultType == .phoneNumber, let number = match.phoneNumber {
        print(number)
    }
}

答案 1 :(得分:1)

您可以使用此正则表达式查看电话号码

1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?

找到匹配(我正在使用当前项目)

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        print("\(results)")
        return results.map { nsString.substring(with: $0.range)}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

以下是测试结果 - enter image description here

答案 2 :(得分:1)

使用两行代码快速实现5种简便方法,这只会帮助您从字符串中获取十进制数字

    File file_obj = new File(this.file); 
    String authorization = "my authorization string";
    Proxy webproxy = new Proxy(Proxy.Type.HTTP, new 
          InetSocketAddress("proxy", <port>));

    OkHttpClient client = new OkHttpClient.Builder().proxy(webproxy).build();      

    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "filename",
        RequestBody.create(MediaType.parse("application/octet-stream"), file_obj)).build();

    Request request = new Request.Builder().header("Authorization", authorization).url(this.url).post(requestBody).build();

    try (Response response = client.newCall(request).execute()){
        if(!response.isSuccessful()) return "NA";
        return (response.body().string());
    }

答案 3 :(得分:0)

此func接收您的字符串并返回检测到的手机数组。它使用NSDataDetector,如果这种机制最终不能满足您的需求,您可能需要构建自己的算法:

func getPhoneNumber(from str: String) -> [String] {
    let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
    let matches = detector.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))

    var resultsArray = [String]()

    for match in matches {
        if match.resultType == .phoneNumber,
            let component = match.phoneNumber {
            resultsArray.append(component)
        }
    }
    return resultsArray
}