-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplacestr.go
More file actions
73 lines (63 loc) · 1.71 KB
/
replacestr.go
File metadata and controls
73 lines (63 loc) · 1.71 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
// RepFuncStr replaces a string with the result of a function
//
// similar to JavaScript .replace(/re/, function(b){})
func (reg *Regexp) RepFuncStr(buf string, rep func(b func(int) []byte) []byte) string {
return string(reg.RE.ReplaceAllFunc([]byte(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
}))
}
// RepFuncBreakStr 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) RepFuncBreakStr(buf string, rep func(b func(int) []byte) ([]byte, bool)) string {
stop := false
return string(reg.RE.ReplaceAllFunc([]byte(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
}))
}
// RepStr 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) RepStr(buf string, rep string) string {
return reg.RE.ReplaceAllString(buf, rep)
}
// RepLitStr replaces a string with another string literal
//
// note: this function does not accept replacements like $1
func (reg *Regexp) RepLitStr(buf string, rep string) string {
return reg.RE.ReplaceAllLiteralString(buf, rep)
}