I am self-studying regular expressions and found an interesting practice problem online that involves writing a regular expression to recognize all binary numbers divisible by 3
Following what Oli Charlesworth says, you can build DFA for divisibility of base b
number by a certain divisor d
, where the states in the DFA represent the remainder of the division.
For your case (base 2 - binary number, divisor d
= 310):
Note that the DFA above accepts empty string as a "number" divisible by 3. This can easily be fixed by adding one more intermediate state in front:
Conversion to theoretical regular expression can be done with the normal process.
Conversion to practical regex in flavors that supports recursive regex can be done easily, when you have got the DFA. This is shown for the case of (base b
= 10, d
= 710) in this question from CodeGolf.SE.
Let me quote the regex in the answer by Lowjacker, written in Ruby regex flavor:
(?!$)(?>(|(?4\g|5\g|6\g|[07]\g|[18]\g|[29]\g|3\g))(|(?[18]\g|[29]\g|3\g|4\g|5\g|6\g|[07]\g))(|(?5\g|6\g|[07]\g|[18]\g|[29]\g|3\g|4\g))(|(?[29]\g|3\g|4\g|5\g|6\g|[07]\g|[18]\g))(|(?6\g|[07]\g|[18]\g|[29]\g|3\g|4\g|5\g))(|(?3\g|4\g|5\g|6\g|[07]\g|[18]\g|[29]\g)))(?$|[07]\g|[18]\g|[29]\g|3\g|4\g|5\g|6\g)
Breaking it down, you can see how it is constructed. The atomic grouping (or non-backtracking group, or a group that behaves possessively) is used to make sure only the empty string alternative is matched. This is a trick to emulate (?DEFINE)
in Perl. Then the groups A
to G
correspond to remainder of 0 to 6 when the number is divided by 7.
(?!$)
(?>
(|(?4 \g|5 \g|6 \g|[07]\g|[18]\g|[29]\g|3 \g))
(|(?[18]\g|[29]\g|3 \g|4 \g|5 \g|6 \g|[07]\g))
(|(?5 \g|6 \g|[07]\g|[18]\g|[29]\g|3 \g|4 \g))
(|(?[29]\g|3 \g|4 \g|5 \g|6 \g|[07]\g|[18]\g))
(|(?6 \g|[07]\g|[18]\g|[29]\g|3 \g|4 \g|5 \g))
(|(?3 \g|4 \g|5 \g|6 \g|[07]\g|[18]\g|[29]\g))
)
(?$| [07]\g|[18]\g|[29]\g|3 \g|4 \g|5 \g|6 \g)