REGEX - 如何在任何地方匹配至少一个特殊字符的字符串集?

时间:2013-05-16 06:23:36

标签: regex

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

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

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

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

2 个答案:

答案 0 :(得分: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
----------------------------------------------------------------------

答案 1 :(得分:3)

如何迭代字符并计算特殊字符,而不是使正则表达式复杂化

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

if count > 1:
    reject()