Regex пройти проверку - PullRequest
       6

Regex пройти проверку

1 голос
/ 29 ноября 2011

Я хотел бы знать, как можно проверить пароль с помощью регулярных выражений.

Я пытался использовать утверждения lookahaed, но мне как-то не удалось.Я не знаю, как сопоставить определенную длину строки.

Мои условия:

  • Не менее 8 символов
  • Не менее одной цифры
  • Как минимум одна нижняя английская буква
  • Как минимум одна верхняя английская буква
  • Как минимум один символ! @ # $% -
  • Только над символамиразрешено

Заранее спасибо!

Ответы [ 4 ]

4 голосов
/ 29 ноября 2011

вы находитесь на правильном шаге с предвзятыми утверждениями.

Ваши требования могут быть разбиты на:

  • (? =. {8,})
  • (? =. * \ Г)
  • (? =. * [А-г])
  • (? =. * [A-Z])
  • (= * [@ # $% -]?.)
  • [\ да-Za-Z @ # $% -] *

Собрав все это, вы получите:

foundMatch = Regex.IsMatch(subjectString, @"^(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%-])[\da-zA-Z!@#$%-]*$");

Что, в свою очередь, можно объяснить этим:

"
^                   # Assert position at the beginning of the string
(?=                 # Assert that the regex below can be matched, starting at this position (positive lookahead)
   .                   # Match any single character that is not a line break character
      {8,}                # Between 8 and unlimited times, as many times as possible, giving back as needed (greedy)
)
(?=                 # Assert that the regex below can be matched, starting at this position (positive lookahead)
   .                   # Match any single character that is not a line break character
      *                   # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   \d                  # Match a single digit 0..9
)
(?=                 # Assert that the regex below can be matched, starting at this position (positive lookahead)
   .                   # Match any single character that is not a line break character
      *                   # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   [a-z]               # Match a single character in the range between “a” and “z”
)
(?=                 # Assert that the regex below can be matched, starting at this position (positive lookahead)
   .                   # Match any single character that is not a line break character
      *                   # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   [A-Z]               # Match a single character in the range between “A” and “Z”
)
(?=                 # Assert that the regex below can be matched, starting at this position (positive lookahead)
   .                   # Match any single character that is not a line break character
      *                   # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   [!@#$%-]            # Match a single character present in the list below
                          # One of the characters “!@#$”
                          # The character “%”
                          # The character “-”
)
[\da-zA-Z!@#$%-]    # Match a single character present in the list below
                       # A single digit 0..9
                       # A character in the range between “a” and “z”
                       # A character in the range between “A” and “Z”
                       # One of the characters “!@#$”
                       # The character “%”
                       # The character “-”
   *                   # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$                   # Assert position at the end of the string (or before the line break at the end of the string, if any)
"
1 голос
/ 29 ноября 2011

Это должно работать для вас

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%-]).{8,}$

Объяснение

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    [0-9]                    any character of: '0' to '9'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    [a-z]                    any character of: 'a' to 'z'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    [A-Z]                    any character of: 'A' to 'Z'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    [!@#$%-]                 any character of: '!', '@', '#', '$',
                             '%', '-'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  .{8,}                    any character except \n (at least 8 times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

Действительно, вы не должны применять такой пароль. Посмотрите этот заслуживающий внимания комикс xkcd для ясного объяснения, почему

За 20 лет работы мы успешно научили всех использовать пароли, которые трудно запомнить людям, но которые трудно угадать компьютерам.

XKCD password strength

0 голосов
/ 29 ноября 2011

Есть ли причина, по которой вам нужно использовать одно регулярное выражение для всех этих правил?Это более распространенный и более читаемый, чтобы проверить каждый в отдельности.Например:

if(pass.length < 8 || ! pass.matches(/[0-9]/) || ! pass.matches(/[a-z]/)
   || ! pass.matches(/[A-Z]/) || ! pass.matches(/[!@#$%-]/)
   || pass.matches(/[^0-9A-Za-z!@#$%-]/))
{
    . . . // reject password
}
0 голосов
/ 29 ноября 2011

Возможно что-то вроде этого:
(Ой, лучше сделайте это как минимум правильно)
расширен

^
(?=[0-9a-zA-Z!@#$%-]{8,}$)
(?=.*[0-9])
(?=.*[a-z])
(?=.*[A-Z])
(?=.*[!@#$%-])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...