The code below is a process to determine whether the mobile number is entered in single-byte alphanumeric characters. At first glance, it seems to work normally, but with this, true is returned regardless of whether the full-width "090-0000-0000" or the half-width "090-0000-0000" is judged, and the full-width cannot be distinguished.
func checkPhoneNum(string: String) -> Bool {
let format = "[0-9]{3}-[0-9]{4}-[0-9]{4}"
let predicate = NSPredicate(format:"SELF MATCHES %@", format)
return predicate.evaluate(with: string)
}
As mentioned above, NSPredicate cannot distinguish between full-width characters, so NSRegularExpression determines as follows. This will return false for full-width and true for half-width.
func checkPhoneNum(string: String) -> Bool {
let format = "[0-9]{3}-[0-9]{4}-[0-9]{4}"
let regexp = try! NSRegularExpression.init(pattern: format, options: [])
let nsString = string as NSString
let matchRet = regexp.firstMatch(in: string, options: [], range: NSRange.init(location: 0, length: nsString.length))
return matchRet != nil
}
http://aryzae.hatenablog.com/entry/2017/12/13/004159
Recommended Posts