1

我在使用以下正则表达式匹配密码时遇到问题。

^[A-Za-z\d[\!\@\#\$\%\^\&\*\(\)\_\+]{1,}]{6,}$

在上面的表达式中,我希望用户在任何地方至少输入一个特殊字符,其余字符应该是字母数字。密码长度不能小于六。

但是上面的表达式不允许用户输入任何特殊字符。谁能告诉我如何限制用户输入至少一个特殊字符?

4

2 回答 2

9

怎么样:

^(?=[\w!@#$%^&*()+]{6,})(?:.*[!@#$%^&*()+]+.*)$

解释:

The regular expression:

(?-imsx:^(?=[\w!@#0^&*()+]{6,})(?:.*[!@#0^&*()+]+.*)$)

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  (?=                      look ahead to see if there is:
----------------------------------------------------------------------
    [\w!@#0^&*()+]{6,}       any character of: word characters (a-z,
                             A-Z, 0-9, _), '!', '@', '#', '0', '^',
                             '&', '*', '(', ')', '+' (at least 6
                             times (matching the most amount
                             possible))
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  (?:                      group, but do not capture:
----------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
----------------------------------------------------------------------
    [!@#0^&*()+]+            any character of: '!', '@', '#', '0',
                             '^', '&', '*', '(', ')', '+' (1 or more
                             times (matching the most amount
                             possible))
----------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
----------------------------------------------------------------------
  )                        end of grouping
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------
于 2013-05-16T08:29:41.473 回答
3

与其使您的正则表达式复杂化,不如迭代字符并计算特殊字符

count = 0
for char in string:
    if isspecial(char):
        count = count+1

if count > 1:
    reject()
于 2013-05-16T06:32:01.713 回答