3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】NSPredicateで全角半角の区別ができないことについて

Posted at

NSPredicateでの全半角の区別

下記のコードは携帯番号が半角英数字で入力されているかを判定する処理です。
一見正常に動きそうですが、これでは全角の「090-0000-0000」と半角の「090-0000-0000」のどちらを判定してもtrueが返ってきて全半角の区別がつきません。

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

NSRegularExpressionでの全半角の区別

上記のようにNSPredicateでは全半角の区別がつかないため、NSRegularExpressionで下記のように判定します。これで全角の場合はfalse、半角の場合はtrueで返ってきます。

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
}

参考

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?