0
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 1 year has passed since last update.

正規表現を使った文字チェック

Last updated at Posted at 2021-03-31

文字チェック

アプリ開発をする上で文字チェックによるセキュリティ管理はとても重要です。
アカウント作成・ログイン機能がついてる場合、メアドやパスワードを入力してもらうと思いますが、その際、パスワードに同じ文字が並んでいたり、メアドの形式が違うのに処理が完了してしまうと、セキュリティ的に良くないです。

メソッド

文字に対する処理なので、Stringをextensionして以下のメソッドを記述すると便利ですよ〜

・同じ文字が3字以上並んでるか判定。
 パスワードに対してのチェックですね。3字以上並んでたらアウト。

    // 同じ字が3つ以上並んでいるか判定
    func isContainContinuousSameChar(count: Int = 3) -> Bool {
        guard count > 1 else { return true }
        let pattern = "(.)\\1{\(count-1)}"
        guard let regex = try? NSRegularExpression(pattern: pattern) else { return false }
        let matches = regex.matches(in: self, range: NSRange(location: 0, length: self.count))
        return matches.count > 0
    }

・使い方

     if password.isContainContinuousSameChar(count: 3) {
         // アラートなりHUD
         return
     }

・半角英数字判定
 全角とか含めてほしくないとこで使える。

    // 半角英数字判定
    func isAlphanumeric() -> Bool {
        let pattern =  "[^A-Za-z0-9]+"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let result = regex.matches(in: self, options: [], range: _NSRange(0..<self.count))
        return result.count > 0
    }

・使い方

    if password.isAlphanumeric() {
        // アラートなりHUD
        return
    }

・メールの形式判定

    // メールの形式判定
    func checkEmail() -> Bool {
        let pattern =  "[A-Z0-9a-z._+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let result = regex.matches(in: self, options: [], range: _NSRange(0.. <self.count))
        return result.count > 0
    }

・使い方

    if !address.checkEmail() {
        // アラートなりHUD
        return
    }

・特殊文字判定
アカウント作成において特殊文字は使ってほしくないです。特殊文字は文字化けの原因になったりするので防ぎたいところです。

    // 特殊文字判定
    func checkSpecialWord() -> Bool {
        let pattern =  "[!@#%$&*!@#%$&*]+"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let result = regex.numberOfMatches(in: self, options: [], range: _NSRange(0..<self.count))
        return result > 0
    }

・使い方

    if displayName.checkSpecialWord() {
       // アラートなりHUD
       return
    }

ハマりどころ

最初はNSPredicateの方が簡単に記述できそうだったのでそっちでやろうとしましたが、半角全角の区別がつかなくなっちゃうみたいなので、少し大変ですがNSRegularExpressionを使ってやりました。

0
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
0
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?