projects > from_scratch > grep.go
1
A grep, from scratch, in Go[github]
1
2
A grep built from scratch in Go with no regex libraries — the
3
pattern is compiled by hand into a token list, and matching is a
4
backtracking DFS where every token reports all the ways it could
5
consume the input, greedy-first.
6
7
Supports ERE-flavored syntax (character classes, anchors,
8
quantifiers including {n,m} ranges, grouping and alternation),
9
capture groups that survive nesting, and multiple and nested
10
backreferences, behind a grep-style CLI with recursive directory
11
walk and a goroutine-per-file fan-out. Built end-to-end as the
12
CodeCrafters 'Build Your Own grep' challenge, including the
13
Backreferences and File Search extensions.
14
15
[Go][GitHub]
16
18
19
func (t Backreference) Match(input []rune, i int, matched []*TokenMatchResult) []*TokenMatchResult {
20
var match *TokenMatchResult
21
for _, m := range matched {
22
if m.GroupNumber == int(t) {
23
match = m
24
}
25
}
26
if match == nil {
27
return nil
28
}
29
30
expected := input[match.Start:match.End]
31
if i+len(expected) > len(input) {
32
return nil
33
}
34
if slices.Equal(expected, input[i:i+len(expected)]) {
35
return []*TokenMatchResult{{Start: i, End: i + len(expected)}}
36
}
37
return nil
38
}
39
40
41
42
43
44
NORMAL~/oleksandr/projects/from_scratch/grep.go.../from_scratch/grep.gomainutf-8
Enter to open · :q to quit
keys
j / kmove the cursor line, or the tree cursor
hfocus the tree; in the tree, fold or go to the parent
l / Enterin the tree, unfold or open the file
gg / Gfirst / last line
clickput the cursor on a line; on README.sh, run the session again
:qquit to the shell
:help ?this table
q / Escclose this