はじめに
元旦、プログラミングを教えている弟から「この正規表現の意味が分からない」と質問が来ました。
//8文字以上で、英小文字、英大文字、数字を1文字以上含む文字列
//※パスワードの形式指定でよくあるやつ
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]{8,}$
う〜ん、兄も分かりません。
分からないところを調べた結果
-
(?=A)
- 前方参照。Aという文字があったら、(?=A)の直前の位置にマッチする。(マッチした位置に戻る)
-
.*
- 任意の文字0文字以上
動作を日本語にすると
- 任意の文字0文字以上+[a-z]にマッチしたら、文頭に戻る
- 任意の文字0文字以上+[A-Z]にマッチしたら、文頭に戻る
- 任意の文字0文字以上+[0-9]にマッチしたら、文頭に戻る
- その後[a-zA-Z0-9]が最低8回繰り返される文字列(+文末)とマッチする
前方参照の「文字ではなく、位置にマッチする」という性質に戸惑いましたが、調べがいがあって楽しかったです。