检查 Swift 中的字符串是否为 3 个字符和 3 个数字

Check if string is 3 chars and 3 number in Swift

我正在尝试创建一个函数来验证我的字符串是否使用此格式

ABC123
First three characters should be letters and the other 3 should be numbers

我不知道如何开始

谢谢

您可以使用字符串的正则表达式匹配来实现,如下所示:

    let str = "ABC123"
    let optRange = str.rangeOfString("^[A-Za-z]{3}\d{3}$", options: .RegularExpressionSearch)
    if let range = optRange {   
        println("Matched")
    } else {
        println("Not matched")
    }

上面的正则表达式要求匹配占据整个字符串(两端的 ^$ 锚点),具有三个字母 [A-Za-z]{3} 和三个数字 \d{3} .

如果您愿意,也可以将其用作扩展:

    extension String {
        var match: Bool {
            return rangeOfString("^[A-Za-z]{3}\d{3}$", options: .RegularExpressionSearch) != nil
        }
    }


    "ABC123".match // true