用于验证 Swift 中 UITextField 的 Civil ID 的正则表达式

Regex for validating the Civil ID in Swift for the UITextField

我有一个具有以下格式的 UITextfield。这是我们通常在海湾国家看到的公民身份证。所以我需要在 Swift.

的 UITextfield 中验证相同的内容

公民身份证格式 - NYYMMDDNNNNN,其中 N 位数字,YY 出生年份的最后两位数字,MM 出生月份,DD 出生日期..

请告诉我如何对此进行验证。

这里是一个如何使用正则表达式的例子

var civilID = "4 88 05 20 8787"
var isValidCivilID: Bool {
    do {
        // the first 0 (?!00) checks that the numbers should not be all zero and d{2} it should have 2 digigts remember it's simple you can make it much complex
        // also if you want space in between or not
        let regex = try NSRegularExpression(pattern: "\d{1} (?!00)\d{2} (?!00)\d{2} (?!00)\d{2} (?!0000)\d{4}", options: .caseInsensitive)
        return regex.firstMatch(in: civilID, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, civilID.characters.count)) != nil
    } catch {
        return false
    }
}

如果您不再次检查格式,那么也请删除正则表达式中的空格,如果 civilID 已正确填写,它将 return true else false

如果您想在字符串扩展中添加这些检查并阅读更多内容,请参阅此 link Swift Extensions, extending Strings