正则表达式重复字符计数

发布于 2024-11-27 14:58:35 字数 110 浏览 2 评论 0原文

如果我有一组像“abcdefghij”这样的字符并使用这些字符,我会使用这些字符随机生成一个密码。例如,生成的密码可以有 6 个字符。如何使用正则表达式验证密码,以使相邻字符不相同并且字符不会重复两次以上?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小嗷兮 2024-12-04 14:58:35

您可以使用类似:

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

Perl 引用,如果不支持,可以删除原子组。


在 Java 正则表达式中,它可以写成:

^(?:(.)(?!\1|(?:.*?\1){2}))*\z

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
不交电费瞎发啥光 2024-12-04 14:58:35

AFAIK,这不能用简单的正则表达式来完成(特别是,确保一个字母最多只出现两次。你可以做一堆像

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

and 之类的表达式(匹配意味着验证失败):

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

但显然这不是一个好主意

。字符不重复在一起的情况也许可以用捕获组来处理,但我几乎肯定不能用正则表达式检查另一个

......为什么痴迷于正则表达式?编程这些检查是微不足道的,正则表达式在一组情况,但并非所有检查都可以使用正则表达式完成。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文