ios - 在 Swift 中检查字符串是否为 3 个字符和 3 个数字

标签 ios string swift nsformatter

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

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")
    }

上面的正则表达式要求匹配占据整个字符串(两端的 ^$ anchor ),具有三个字母 [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

关于ios - 在 Swift 中检查字符串是否为 3 个字符和 3 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654695/

相关文章:

ios - iOS8键盘事件无法正确执行

ios - swift4的facebook ios url方案

Swift 枚举 : Getting enum value for string enum from int value

c++ - std::string 到 SecByteBlock 的转换

ios - 从核心数据中删除多余数据的有效方法

ios - 在 ios 中上传后如何从 firebase 获取缩略图?

python - 将字符串列表转换为python中的列表

xcode - 获取与 Swift 一起运行的 Phillips Hue 框架 SDK

ios - 无法在 Objective-C 项目中使用 RAMAnimatedTabBarController?

iphone - 使用按钮更改 iphone 应用程序语言,无需重新启动应用程序