如何在 Swift 中匹配两个相似的电话号码,但一个包含国家/地区代码,另一个包含或不包含国家/地区代码

问题描述 投票:0回答:3

我试图在 swift 中匹配两个相似的电话号码,但其中一个前面有国家/地区代码,另一个可能会有所不同。 例如,我希望这 2 个电话号码匹配:

0499999999

+32499999999

我希望这对世界各地的任何电话号码都有效。是否有一个正则表达式,或者我可以下载一个 pod 来执行此操作?

谢谢

ios regex swift contacts
3个回答
1
投票

使用 PhoneNumberKit 解析 PhoneNumber。

https://github.com/marmelroy/PhoneNumberKit

喜欢:

let rawNumberArray = ["0291 12345678", "+49 291 12345678", "04134 1234", "09123 12345"]
let phoneNumbers = phoneNumberKit.parse(rawNumberArray)
let phoneNumbersCustomDefaultRegion = phoneNumberKit.parse(rawNumberArray, withRegion: "DE",  ignoreType: true)

0
投票

您可以制作一个国家和国家代码的查找表,并通过电话查看他们的区域设置是什么

let countrycode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as? String

let countryPrefixes = ["IE": "+353", 
                       "US": "+1",
                        etc...

let prefix = countryPrefixes[countrycode]

一旦有了前缀,您应该就可以查看其余的数字。

或者你可以使用这个 github 库 https://github.com/rmaddy/RMPhoneFormat,它似乎已经为你完成了这项工作。

当然,这是假设您希望输入到设备中的电话号码在电话运行的区域设置中有效。


0
投票

对于接受的答案,我们需要了解该地区。因此,如果我们知道国家/地区代码,这里有一个解决方案,以避免项目中的任何第三方依赖。

func isPhoneNumberEquals(_ firstNumber: String, with secondNumber: String) -> Bool {

    // If two numbers are equal directly, return true
    if firstNumber == secondNumber {
        return true
    }
    var countryCode: String? = nil
    if firstNumber.hasSuffix(secondNumber) {
        countryCode = firstNumber.replacingOccurrences(of: secondNumber, with: "")
    }
    if secondNumber.hasSuffix(firstNumber) {
        countryCode = secondNumber.replacingOccurrences(of: firstNumber, with: "")
    }
    guard let countryCode else {
    // The numbers aren't same as they don't matched with suffix
        return false
    }
    if countryCode == myCountryCode {
    // The country code and the phone number without country code both are matched for the given numbers.
        return true
    }
    let digitDifference = myCountryCode.replacingOccurrences(of: countryCode, with: "")
    // Sometimes there is a common '0' in phone number and country code. If this is not the case, return false
    return digitDifference == "0"
}

注意:如果您发现任何极端情况,请在下面评论。我们也将解决/改进我们的生产代码:P.

© www.soinside.com 2019 - 2024. All rights reserved.