swift ios alpha numeric regex that allows underscores and dashes

时间:2016-08-13 13:25:14

标签: ios regex swift xcode

I am using this lib for validation and are trying to add my own regex.

What I want to do is to make a regex that allows alphanumeric A-Z 0-9 together with dashes and unserscores -_

I have tryed let regex = "[a-zA-Z0-9_-]" but I cant get it to work.

I also want the regex to not only allow english letters, but all languishes.

The lib works cause I have made another regex that only allows ints 0-9 which works

let intRegex = "^[0-9]*$"

1 个答案:

答案 0 :(得分:0)

以@charsi 的回答为基础

extension String {
    var isAlphanumericDashUnderscore: Bool {
        get {
            let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9_-]*$", options: .caseInsensitive)
            return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
        }
    }
}