简体   繁体   English

二进制数的正则表达式可被5整除

[英]Regular Expression for Binary Numbers Divisible by 5

I want to write a regular expression for Binary Numbers Divisible by 5. 我想写一个二进制数的正则表达式,可以被5整除。
I have already done the regular expressions for Binary Numbers Divisible by 2 and for 3 but I couldn't find one for 5. 我已经完成了二进制数的正则表达式,可以被2和3整除,但我找不到一个用于5。

Any suggestions? 有什么建议?

(0|1(10)*(0|11)(01*01|01*00(10)*(0|11))*1)*

Add ^$ to test it with regexp. 添加^$以使用regexp对其进行测试。 See it working here . 看到它在这里工作


You can build a DFA and convert it to regular expression. 您可以构建DFA并将其转换为正则表达式。 The DFA was already built in another answer . DFA已经在另一个答案中构建。 You can read it, it is very well explained. 你可以阅读它,它解释得非常好。
The general idea is to remove nodes, adding edges. 一般的想法是删除节点,添加边。 之前

Becomes: 变为:

后


Using this transformation and the DFA from the answer I linked, here are the steps to get the regular expression: 使用此转换和我链接的答案中的DFA,以下是获取正则表达式的步骤: 步骤1 第2步 第三步: 第4步 STEP5

2^0 =  1 =  1 mod 5
2^1 =  2 =  2 mod 5
2^2 =  4 = -1 mod 5
2^3 =  8 = -2 mod 5
2^4 = 16 =  1 mod 5
2^5 = 32 =  2 mod 5
   ...     -1 mod 5
   ...     -2 mod 5

So we have a 1, 2, -1, -2 pattern. 所以我们有一个1,2,-1,-2模式。 There are two subpatterns where only the sign of the number alternates: Let n is the digit number and the number of the least significant digit is 0; 有两个子模式,其中只有数字的符号交替:设n是数字编号,最低有效数字的编号是0; odd pattern is 奇怪的模式是

(-1)^(n)

and even pattern is 甚至模式是

2x((-1)^(n))

So, how to use this? 那么,如何使用呢?

Let the original number be 100011, divide the numbers digits into two parts, even and odd. 让原始数字为100011,将数字数字分成偶数和奇数两部分。 Sum each parts digits separately. 分别对每个零件数字求和。 Multiply sum of the odd digits by 2. Now, if the result is divisible by sum of the even digits, then the original number is divisible by 5, else it is not divisible. 将奇数位的总和乘以2.现在,如果结果可以被偶数位的总和整除,则原始数字可以被5整除,否则它不可被整除。 Example: 例:

100011
1_0_1_ 1+0+1 = 2
_0_0_1 0+0+1 = 1; 1x2 = 2

2 mod(2) equals 0? Yes. Therefore, original number is divisible.

How to apply it within a regex? 如何在正则表达式中应用它? Using callout functions within a regex it can be applied. 使用正则表达式中的标注函数可以应用它。 Callouts provide a means of temporarily passing control to the script in the middle of regular expression pattern matching. 标注提供了一种在正则表达式模式匹配过程中临时将控制传递给脚本的方法。

However, ndn's answer is more appropriate and easier, therefore I recommend to use his answer. 但是,ndn的答案更合适也更容易,因此我建议使用他的答案。

但是,“^(0 | 1(10)*(0 | 11)(01 * 01 | 01 * 00(10)*(0 | 11)) 1) $”匹配空字符串。

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

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