-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.go
More file actions
73 lines (63 loc) · 1.65 KB
/
replace.go
File metadata and controls
73 lines (63 loc) · 1.65 KB
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
package regex
// RepFunc replaces a string with the result of a function
//
// similar to JavaScript .replace(/re/, function(b){})
func (reg *Regexp) RepFunc(buf []byte, rep func(b func(int) []byte) []byte) []byte {
return reg.RE.ReplaceAllFunc(buf, func(b []byte) []byte {
m := reg.RE.FindSubmatch(b)
r := rep(func(g int) []byte {
if g < 0 || g >= len(m) {
return []byte{}
}
return m[g]
})
if r == nil {
return []byte{}
}
return r
})
}
// RepFuncBreak replaces a string with the result of a function
// and gives you the option to break the loop
//
// similar to JavaScript .replace(/re/, function(b){})
//
// return true to continue loop, false to break loop
func (reg *Regexp) RepFuncBreak(buf []byte, rep func(b func(int) []byte) ([]byte, bool)) []byte {
stop := false
return reg.RE.ReplaceAllFunc(buf, func(b []byte) []byte {
if stop {
return b
}
m := reg.RE.FindSubmatch(b)
r, next := rep(func(g int) []byte {
if g < 0 || g >= len(m) {
return []byte{}
}
return m[g]
})
if !next {
stop = true
}
if r == nil {
return []byte{}
}
return r
})
}
// Rep replaces a string with another string
//
// this function will replace things in the result like $1 with your capture groups
//
// use $0 to use the full regex capture group
//
// use ${123} to use numbers with more than one digit
func (reg *Regexp) Rep(buf []byte, rep []byte) []byte {
return reg.RE.ReplaceAll(buf, rep)
}
// RepLit replaces a string with another string literal
//
// note: this function does not accept replacements like $1
func (reg *Regexp) RepLit(buf []byte, rep []byte) []byte {
return reg.RE.ReplaceAllLiteral(buf, rep)
}