用于代码优化的正则表达式组合

时间:2017-07-11 04:16:12

标签: regex

是否可以使用正则表达式组合这些标准?

至少包含8个字符,并至少包含以下三种字符:

  • 大写字母alpha(A-Z)
  • 号码(0-9)
  • 小写字母alpha(a-z)
  • 特殊字符(,!$%^& *()_ + |〜 - =`{} []:&#34 ;;'<>?,/)

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。
您使用的正则表达式引擎必须支持条件(?(cond)yes|no)

话虽如此,如果你使用任何其他角色,则使用点.

^(?=.{8})(?:.*?(?:(?(1)(?!))([A-Z])|(?(2)(?!))([a-z])|(?(3)(?!))([0-9])|(?(4)(?!))([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~]))){3,4}.*$

扩展

 ^                                             # BOS
 (?= .{8} )                                    # At least 8 chars
 (?:                                           # Require 3 out of the 4 types
      .*? 
      (?:
           (?(1)
                (?!)
           )
           ( [A-Z] )                                     # (1), Upper
        |  
           (?(2)
                (?!)
           )
           ( [a-z] )                                     # (2), Lower
        |  

           (?(3)
                (?!)
           )
           ( [0-9] )                                     # (3), Digit
        |  
           (?(4)
                (?!)
           )
           ( [!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~] )       # (4), Special
      )
 ){3,4}
 .* 
 $                                             # EOS

如果您只想在ascii范围内允许非空格,请使用此

^(?=.{8})(?:[a-zA-Z0-9!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~]*?(?:(?(1)(?!))([A-Z])|(?(2)(?!))([a-z])|(?(3)(?!))([0-9])|(?(4)(?!))([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~]))){3,4}[a-zA-Z0-9!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~]*$

扩展

 ^                                             # BOS
 (?= .{8} )                                    # At least 8 chars
 (?:                                           # Require 3 out of the 4 types
      [a-zA-Z0-9!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~]*? 
      (?:
           (?(1)
                (?!)
           )
           ( [A-Z] )                                     # (1), Upper
        |  
           (?(2)
                (?!)
           )
           ( [a-z] )                                     # (2), Lower
        |  

           (?(3)
                (?!)
           )
           ( [0-9] )                                     # (3), Digit
        |  
           (?(4)
                (?!)
           )
           ( [!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~] )       # (4), Special
      )
 ){3,4}
 [a-zA-Z0-9!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~]* 
 $