简体   繁体   English

偶数个 0 或奇数个 1 的二进制数的最短正则表达式

[英]Shortest regex for binary number with even number of 0s or odd number of 1s

Write an expression that contains an even number of 0s or an odd number of 1s编写一个包含偶数个 0 或奇数个 1 的表达式

I got it down to:我把它归结为:

1*(01*01*)* + 0*10*(10*10*)*

where the first part represents an even number of 0s and the second part an odd number of 1s其中第一部分表示偶数个 0,第二部分表示奇数个 1

However, there's supposed to be a simplified solution that I'm not seeing.但是,应该有一个我没有看到的简化解决方案。 Any tips?任何提示?

Odd-1s part: 0*1(0|10*1)*奇数 1 部分: 0*1(0|10*1)*

Even-0s part, depends: Even-0s 部分,取决于:

  1. Empty string is correct: (1|01*0)*空字符串是正确的: (1|01*0)*
  2. No-0s is even-0s: (1|01*0)+ No-0s 是偶数-0s: (1|01*0)+
  3. Must have at least two 0s: 1*(01*01*)+ (as in OP)必须至少有两个 0: 1*(01*01*)+ (如在 OP 中)

old answer: correct under case 1 and 2旧答案:在案例 1 和 2 下正确

(1*(01*0)*)+ | 0*1(0*(10*1)*)*

Kudos to @OGHaza for helpful comments.感谢@OGHaza 提供有用的评论。

利用偶数长度字符串始终满足您的约束这一事实:

^(([01]{2})*|1*(01*01*)*)$

Define "shortest".定义“最短”。 If you're looking for the shortest evaluation time (ie fastest) then make sure you do not use capture groups.如果您正在寻找最短的评估时间(即最快),请确保您不使用捕获组。

here's an example in javascript这是javascript中的一个例子

^(?:1*(?:01*0)*)+|0*1(?:0*(?:10*1)*)*$

which shows as 20% faster than this expression that uses capture groups but will give you the same answer它比使用捕获组的这个表达式快 20%,但会给你相同的答案

^(1*(01*0)*)+|0*1(0*(10*1)*)*$

我发现的最简单的解决方案是:

1+0(0+1)((1+0)(1+0))*

用最少的符号,

1*(01*01*)*

这个表达式怎么样:

(1(11)*+(00)*)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM