使用DFA
here,我们可以通过以下方式制作正则表达式,其中A,B,C表示DFA的状态.
A = 1B + 0A
B = 1A + 0C
C = 1C + 0B
C = 1*0B // Eliminate recursion
B = 1A + 0(1*0B)
B = 01*0B + 1A
B = (01*0)*1A // Eliminate recursion
A = 1(01*0)*1A + 0A
A = (1(01*0)*1 + 0)A
A = (1(01*0)*1 + 0)* // Eliminate recursion
导致PCRE正则表达式如下:
/^(1(01*0)*1|0)+$/
Perl测试/示例:
use strict;
for(qw(
11
110
1001
1100
1111
0
1
10
111
)){
print "$_ (",eval "0b$_",") ";
print /^(1(01*0)*1|0)+$/? "matched": "didnt match";
print "\n";
}
11 (3) matched
110 (6) matched
1001 (9) matched
1100 (12) matched
1111 (15) matched
0 (0) matched
1 (1) didnt match
10 (2) didnt match
111 (7) didnt match