开发者

regex repeated character count

开发者 https://www.devze.com 2023-03-24 19:27 出处:网络
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 h开发者_C百科ave, for example, 6 characters. H

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 h开发者_C百科ave, for example, 6 characters. How to validate a password using regex so that tho neighbor characters are not identical and a character does not repeat more that twice?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号