Regular Expression for Binary Numbers Divisible by 5
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. 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; 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. 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. 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.
(0|1(10)*(0|11)(01*01|01*00(10)*(0|11))*1)*
Add ^$
to test it with regexp. See it working here.
You can build a DFA and convert it to regular expression. The DFA was already built in another answer. 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:
(EDIT: Note that the labels "Q3" and "Q4" have been mistakenly swapped in the diagram. These states represent the remainder after modulus 5.)