-
Notifications
You must be signed in to change notification settings - Fork 2
/
RegEx.rb
150 lines (138 loc) · 2.86 KB
/
RegEx.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
class RegEx
def isNullable() raise "" end
def derive(c) raise "" end
def matches(string)
if string.size == 0
self.isNullable
else
self.derive(string[0]).matches(string[1..-1])
end
end
end
class Empty < RegEx
def isNullable
false
end
def derive(c)
self
end
end
class Blank < RegEx
def isNullable
true
end
def derive(c)
Empty.new
end
end
class Primitive < RegEx
def initialize(c)
@c = c
end
def isNullable
false
end
def derive(c)
if @c == c
Blank.new
else
Empty.new
end
end
end
class Choice < RegEx
def initialize(this, that)
@this = this
@that = that
end
def isNullable
@this.isNullable || @that.isNullable
end
def derive(c)
Choice.new(@this.derive(c), @that.derive(c))
end
end
class Repetition < RegEx
def initialize(base)
@base = base
end
def isNullable
true
end
def derive(c)
Sequence.new(@base.derive(c), self)
end
end
class Sequence < RegEx
def initialize(left, right)
@left = left
@right = right
end
def isNullable
@left.isNullable && @right.isNullable
end
def derive(c)
if @left.isNullable
Choice.new(Sequence.new(@left.derive(c), @right), @right.derive(c))
else
Sequence.new(@left.derive(c), @right)
end
end
end
class Intersection < RegEx
def initialize(this, that)
@this = this
@that = that
end
def isNullable
@this.isNullable && @that.isNullable
end
def derive(c)
Intersection.new(@this.derive(c), @that.derive(c))
end
end
class Difference < RegEx
def initialize(left, right)
@left = left
@right = right
end
def isNullable
@left.isNullable && [email protected]
end
def derive(c)
Difference.new(@left.derive(c), @right.derive(c))
end
end
class Complement < RegEx
def initialize(base)
@base = base
end
def isNullable
end
def derive(c)
Complement.new(@base.derive(c))
end
end
puts Empty.new.matches("anything")
puts Blank.new.matches("anything")
puts Blank.new.matches("")
puts Primitive.new('c').matches('c')
f = Primitive.new 'f'
puts f.matches 'f'
o = Primitive.new 'o'
foo = Sequence.new(f, Sequence.new(o, o))
puts foo.matches("foo")
puts foo.matches("bar")
b = Primitive.new 'b'
a = Primitive.new 'a'
r = Primitive.new 'r'
bar = Sequence.new(b, Sequence.new(a, r))
puts bar.matches 'bar'
foobar = Choice.new(foo, bar)
puts foobar.matches 'foo'
puts foobar.matches 'bar'
puts foobar.matches 'foobar'
foobarstar = Repetition.new foobar
puts foobarstar.matches 'foobarfoo'
puts foobarstar.matches 'foobarfoof'