-
Notifications
You must be signed in to change notification settings - Fork 1
/
txtmsk.go
101 lines (74 loc) · 1.68 KB
/
txtmsk.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
101
package txtmsk
import (
"regexp"
"strings"
"github.com/nissy/txtmsk/mask"
)
var (
inlineMarkStart = "<msk>"
inlineMarkEnd = "</msk>"
)
func TryMask(m *mask.Mask, text string) (string, error) {
mText, err := inLineMask(m, text)
if err != nil {
return "", err
}
if mText != text {
return mText, nil
}
mText, err = m.Mask(text)
if err != nil {
return "", err
}
return mText, nil
}
func TryUnMask(m *mask.Mask, text string) (string, error) {
umText, err := inLineUnMask(m, text)
if err != nil {
return "", err
}
if umText != text {
return umText, nil
}
if !newInLineRegexp().MatchString(umText) {
umText, err = m.UnMask(text)
if err != nil {
return "", err
}
}
return umText, nil
}
func inLineMask(m *mask.Mask, text string) (string, error) {
for _, v := range newInLineRegexp().FindAllStringSubmatch(text, -1) {
line, err := m.Mask(v[1])
if err != nil {
return "", err
}
text = replaceInLine(text, v[0], line)
}
return text, nil
}
func inLineUnMask(m *mask.Mask, text string) (string, error) {
for _, v := range newInLineRegexp().FindAllStringSubmatch(text, -1) {
line, err := m.UnMask(v[1])
if err != nil {
continue
}
text = replaceInLine(text, v[0], line)
}
return text, nil
}
func newInLineRegexp() *regexp.Regexp {
return regexp.MustCompile(newInlineMark(`([\s\S]+?)`))
}
func newInlineMark(element string) string {
return inlineMarkStart + element + inlineMarkEnd
}
func replaceInLine(src, old, new string) string {
return strings.Replace(src, old, newInlineMark(new), 1)
}
func TrimInLineTag(src string) string {
return strings.Replace(
strings.Replace(src, inlineMarkStart, "", -1),
inlineMarkEnd, "", -1)
}