4
3

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.

2023年の正規表現はじめ(パスワードの形式指定)

Posted at

はじめに

元旦、プログラミングを教えている弟から「この正規表現の意味が分からない」と質問が来ました。

//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回繰り返される文字列(+文末)とマッチする

前方参照の「文字ではなく、位置にマッチする」という性質に戸惑いましたが、調べがいがあって楽しかったです。

参考文献

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?