包含至少两个 0 和至少一个 1 的所有二进制字符串的正则表达式?

发布于 2024-12-10 21:32:06 字数 67 浏览 6 评论 0原文

我想它会是(E0 * 0 * EUE1 * E)? 其中 E 是我的字母表的集合,至少有 2 个 0 和至少 1 个 1

Im thinking it would be (E0*0*EUE1*E)?
where E is the set of my alphabet, with at least 2 0s and at least 1 1

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

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

发布评论

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

评论(4

始于初秋 2024-12-17 21:32:07

尝试这个表达式:

^(.*0.*0.*1.*)|(.*0.*1.*0.*)|(.*1.*0.*0.*)$

编辑
可以简化为:

^.*(0.*0.*1)|(0.*1.*0)|(1.*0.*0).*$

Try this expression:

^(.*0.*0.*1.*)|(.*0.*1.*0.*)|(.*1.*0.*0.*)$

EDIT
Could be simplified to:

^.*(0.*0.*1)|(0.*1.*0)|(1.*0.*0).*$
满身野味 2024-12-17 21:32:07

如果您被允许使用前瞻,我将这样做:(在带有注释的 PHP 自由间距模式下。)

$re = '/
    # Binary strings that include at least two 0s and at least one 1.
    ^                  # Anchor to start of string.
    (?=(?:[^0]*0){2})  # at least two 0s. 
    (?=[^1]*1)         # at least one 1.
    [+\-]?             # Optional leading sign.
    [01]+              # Match string of binary digits.
    $                  # Anchor to end of string.
    /x';

请注意,您可以在字符串的开头放置任意数量的前瞻(其在逻辑 < 中工作) code>AND 方式),指定多个逻辑要求。

If you are allowed to use lookahead, here is how I'd do it: (in PHP free-spacing mode with comments.)

$re = '/
    # Binary strings that include at least two 0s and at least one 1.
    ^                  # Anchor to start of string.
    (?=(?:[^0]*0){2})  # at least two 0s. 
    (?=[^1]*1)         # at least one 1.
    [+\-]?             # Optional leading sign.
    [01]+              # Match string of binary digits.
    $                  # Anchor to end of string.
    /x';

Note that you may place any number of lookaheads at the beginning of the string (which work in a logical AND manner), to specify multiple logical requirements.

背叛残局 2024-12-17 21:32:07

建议的解决方案是错误的,因为它还会接受 000000000 其中 E={0,1}。请注意,1* 表示任意数量的 1 [包括无]

E* * (0E*0E*1+0E*1E*0+1E*0E*0) * E* 都可以:所有可能0,0,1 的排列,并尽可能插入 E* [这样您就可以在所需元素之间/之前插入任意数量的字符]。在正则表达式语法中,它是: .*(0.*0.*1|0.*1.*0|1.*0.*0).*

The suggested solution is wrong, since it will also accept 000000000 where E={0,1}. note that 1* means any number of 1's [including none]

E* * (0E*0E*1+0E*1E*0+1E*0E*0) * E* would work: all possible permutations of 0,0,1, and insert E* wherever possible [so you can insert any numbers of characters between/before the required elements]. In regex syntax it is: .*(0.*0.*1|0.*1.*0|1.*0.*0).*

梦里南柯 2024-12-17 21:32:07

(.*00+.1+.)|(.* 1+ .* 00+.*)

以上是自我解释

。是任意字符
+ 是一个或多个

(.*00+.1+.)|(.* 1+ .* 00+.*)

the above is self explaining

. is any character
+ is one or more

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