regex repeated character count

五迷三道 提交于 2019-11-30 14:28: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, 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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6929614/regex-repeated-character-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!