Go言語でパスワードの正規表現を書こうとしています。
実現したい内容は半角英字、数字、記号(ASCIIで!から〜まで)をそれぞれ1種類以上を含む6文字以上かどうかをチェックする正規表現です。
Go言語では肯定先読みをサポートしていないため他言語のような正規表現ができません。
また、https://teratail.com/questions/377534 の質問を参考に単一の正規表現を使うのではなく、段階的にチェックする方法にしようとしています。
しかし、!から~の正規表現を!-~でプログラムに渡すと、記号を使っていない文字列でも含まれているという結果になり、うまくいきません。
Go
1package main 2 3import ( 4 "regexp" 5 "testing" 6) 7 8func MatchPassword(password string) bool { 9 if len(password) < 6 { // 6文字以上か判定 10 return false 11 } 12 reg := []*regexp.Regexp{ 13 regexp.MustCompile(`[A-Za-z]`), 14 regexp.MustCompile(`\d`), 15 regexp.MustCompile(`[!-~]`), 16 } 17 for _, r := range reg { 18 if r.FindString(password) == "" { 19 return false 20 } 21 } 22 return true 23} 24 25func TestMatchPassword(t *testing.T) { 26 cases := []struct { 27 input string 28 want bool 29 }{ 30 {"1aZ", false}, // 6文字未満だからだめ 31 {"zJmsZJiKeS", false}, // 数字と記号がないからだめ 32 {"v0x51aip1t", false}, // 記号がないのにtrueが帰ってきているので、[!-~]の正規表現が正しくないことまではわかります 33 } 34 35 for i, p := range cases { 36 got := MatchPassword(p.input) 37 if got != p.want { 38 t.Errorf("unexpected ExcelColumn result, case=%d, input=%s, got=%v, want=%v", 39 i+1, p.input, got, p.want) 40 } 41 } 42}

回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/02/14 09:30
2022/02/14 11:21