-
Notifications
You must be signed in to change notification settings - Fork 4
/
regex.v
85 lines (70 loc) · 1.22 KB
/
regex.v
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
module vom
// https://www.cnblogs.com/baiyuxuan/p/15430458.html
// 从字符串生成Regex
pub struct Regex {
expr string
mut: ind int
}
fn (r Regex) peek() char {
return expr[ind]
}
fn (r Regex) next() char {
c := expr[ind]
ind ++
return c
}
fn (r Regex) read(c char) ! {
if c != next() {
return error('expected: ${c}')
}
}
fn (r Regex) end() bool {
return ind == expr.len
}
fn (r Regex) parse() ! {
ind = 0
return parse_expr()
}
// elem = char | (expr)
fn (r Regex) parse_elem() ! {
if peek() == `(` {
next()
rr := parse_expr()
read(`)`)
return rr
} else if peek() == `.` {
next()
return any()
} else {
return ch(next())
}
}
// factor = elem* | elem+ | elem
fn (r Regex) parse_factor() ! {
mut r := parse_elem()
if !end() && peek() == `*` {
r = r.zeroOrMore()
next()
} else if !end() && peek() == `+` {
r = r.oneOrMore()
next()
}
return r
}
// term = factor factor ... factor
fn (r Regex) parse_term() ! {
mut r := parse_factor()
for !end() && peek() != ')' && peek() != '|' {
r = r.concat(parseFactor())
}
return r
}
// expr = term|term|...|term
fn (r Regex) parse_expr() ! {
mut r := parse_term()
for !end() && peek() == '|' {
next()
r = r.or(parse_term())
}
return r
}