[Swift] About the inability to distinguish between full-width and half-width characters with NS Predicate

Distinguishing full-width characters with NS Predicate

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

Distinguishing full-width characters in NSRegularExpression

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
}

reference

http://aryzae.hatenablog.com/entry/2017/12/13/004159

Recommended Posts

[Swift] About the inability to distinguish between full-width and half-width characters with NS Predicate
[Java] Align characters even with mixed half-width and full-width characters
A story about using the CoreImage framework to erase stains with Swift and implement a blur erase function
About the difference between irb and pry
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
[Rails / ActiveRecord] About the difference between create and create!
Distinguish between integers and decimals with regular expressions
[Ruby] I thought about the difference between each_with_index and each.with_index
[Rails] I learned about the difference between resources and resources
Convert the array of errors.full_messages to characters and output
About the difference between classes and instances in Ruby
About the relationship between HTTP methods, actions and CRUD
Arbitrate the fight between PowerMock and jacoco with Gradle
[Swift] UITextField taught me the difference between nil and ""