-
Notifications
You must be signed in to change notification settings - Fork 6
/
match_data.v
61 lines (56 loc) · 1.37 KB
/
match_data.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
module pcre
struct MatchData {
pub:
re &C.pcre // A pointer to pcre structure
regex &Regex
ovector []int
str string
group_size int
mut:
pos int
}
// valid_group checks if group index is valid
pub fn (m MatchData) valid_group(index int) bool {
return -m.group_size <= index && index < m.group_size
}
// get returns a matched group based on index
// * (.+) hello (.+) -> 'This is a simple hello world'
// * get(0) -> This is a simple hello world
// * get(1) -> This is a simple
// * get(2) -> world
// * get(3) -> Error!
pub fn (m MatchData) get(index_ int) !string {
mut index := index_
if !m.valid_group(index) {
return error('Index out of bounds')
}
if index < 0 {
index += m.group_size
}
start := m.ovector[index * 2]
end := m.ovector[index * 2 + 1]
if start < 0 || end > m.str.len {
return error('Match group is invalid')
}
substr := m.str.substr(start, end)
return substr
}
// get_all returns all matched groups
pub fn (m MatchData) get_all() []string {
mut res := []string{}
for i := 1; true; i++ {
substr := m.get(i) or { break }
res << substr
}
return res
}
// next iterates over all pattern matches
pub fn (mut m MatchData) next() ?MatchData {
if m0 := m.get(0) {
ret := m.regex.match_str(m.str, if m.pos == 0 { 0 } else { m.pos + m0.len - 1 },
m.regex.options) or { return none }
m.pos += m0.len
return ret
}
return none
}