2012年12月24日月曜日

正規表現の先読み

msdnを見ていたら、こんなソースを見つけた。

public void OnValidatePassword(object sender,
                              ValidatePasswordEventArgs args)
{
  System.Text.RegularExpressions.Regex r =
    new System.Text.RegularExpressions.Regex(@"(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,})");


  if (!r.IsMatch(args.Password))
  {
    args.FailureInformation =
      new HttpException("Password must be at least 6 characters long and " +
                        "contain at least one number and one special character.");
    args.Cancel = true;
  }
}
パスワードの入力チェックで
  • 長さが6文字以上
  • 数字が1つ以上含まれている
  • 英数字以外の文字が1つ以上含まれている
という3つの用件を
(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,})
という一つの正規表現でチェックしていた。 正規表現の『(?=)』は先読みと呼ばれるもので、正規表現の先読みについて解説してみる がとても参考になった。

0 件のコメント:

コメントを投稿