regex repeated character count

前端 未结 2 782
时光取名叫无心
时光取名叫无心 2021-01-01 07:18

If I have a set of characters like \"abcdefghij\" and using this characters, I generate random a password using this characters. A generated password can have, for example,

相关标签:
2条回答
  • 2021-01-01 08:07

    You could use something like:

    /^
      (?:(.)
         (?!\1)           # neighbor characters are not identical
         (?!(?>.*?\1){2}) # character does not occur more than twice
      )*
    \z/x
    

    Perl quoting, the atomic group can be removed if not supported.


    In Java regex it could be written like:

    ^(?:(.)(?!\1|(?:.*?\1){2}))*\z
    
    0 讨论(0)
  • 2021-01-01 08:20

    AFAIK, this cannot be done with a simple regexp (particularly, ensuring that a letter only appears twice at max. You could do a bunch of expressions like

    [^a]*(a[^a]*(a[^a]*))
    [^b]*(b[^b]*(b[^b]*))
    ....
    

    and also (matching means the validation failed):

    [^a]*aa[^a]*
    [^b]*bb[^b]*
    

    but obviously this is not good idea.

    The condition that the characters do not repeat together maybe can treated with capturing groups, but I am almost sure the other one cannot be checked with regex.

    BTW... why the obsession with regex? Programming these checks are trivial, regex is useful in a set of cases but not every check can be done with regex.

    0 讨论(0)
提交回复
热议问题