forked from marcomaggi/cre2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathre2util.go
100 lines (79 loc) · 1.33 KB
/
re2util.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package re2
import ()
// $nを\\nへ置換
// (Goのregexpのsequenceは$nだが、re2のsequenceは\\n)
func replaceRE2Sequences(b []byte) []byte {
var buf []byte
escape := false
digit := false
for _, x := range b {
n := int(x) - int('0')
switch {
case x == '$':
digit = false
if escape {
buf = append(buf, '$')
}
escape = true
break
case n >= 0 && n <= 9:
if !digit && escape {
buf = append(buf, '\\')
digit = true
escape = false
}
buf = append(buf, x)
break
default:
digit = false
if escape {
buf = append(buf, '$')
escape = false
}
buf = append(buf, x)
break
}
}
if escape {
buf = append(buf, '$')
}
return buf
}
func replaceRE2InvalidSequences(b []byte) []byte {
var buf []byte
escape := false
digit := false
for _, x := range b {
n := int(x) - int('0')
switch {
case x == '\\':
digit = false
if escape {
buf = append(buf, '\\')
}
escape = true
break
case n >= 0 && n <= 9:
if !digit && escape {
buf = append(buf, '\\')
buf = append(buf, '\\')
digit = true
escape = false
}
buf = append(buf, x)
break
default:
digit = false
if escape {
buf = append(buf, '\\')
escape = false
}
buf = append(buf, x)
break
}
}
if escape {
buf = append(buf, '\\')
}
return buf
}