-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
extract.go
78 lines (70 loc) · 1.76 KB
/
extract.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
package main
import (
"regexp"
"strings"
)
const (
urlPattern = `https?://[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)]+`
mentionPattern = `@[a-zA-Z0-9.]+`
emojiPattern = `:[a-zA-Z0-9]+:`
tagPattern = `\B#\S+`
)
var (
urlRe = regexp.MustCompile(urlPattern)
mentionRe = regexp.MustCompile(mentionPattern)
emojiRe = regexp.MustCompile(emojiPattern)
tagRe = regexp.MustCompile(tagPattern)
)
type entry struct {
start int64
end int64
text string
}
func extractLinks(text string) []entry {
var result []entry
matches := urlRe.FindAllStringSubmatchIndex(text, -1)
for _, m := range matches {
result = append(result, entry{
text: text[m[0]:m[1]],
start: int64(len([]rune(text[0:m[0]]))),
end: int64(len([]rune(text[0:m[1]])))},
)
}
return result
}
func extractMentions(text string) []entry {
var result []entry
matches := mentionRe.FindAllStringSubmatchIndex(text, -1)
for _, m := range matches {
result = append(result, entry{
text: strings.TrimPrefix(text[m[0]:m[1]], "@"),
start: int64(len([]rune(text[0:m[0]]))),
end: int64(len([]rune(text[0:m[1]])))},
)
}
return result
}
func extractEmojis(text string) []entry {
var result []entry
matches := emojiRe.FindAllStringSubmatchIndex(text, -1)
for _, m := range matches {
result = append(result, entry{
text: text[m[0]:m[1]],
start: int64(len([]rune(text[0:m[0]]))),
end: int64(len([]rune(text[0:m[1]])))},
)
}
return result
}
func extractTags(text string) []entry {
var result []entry
matches := tagRe.FindAllStringSubmatchIndex(text, -1)
for _, m := range matches {
result = append(result, entry{
text: strings.TrimPrefix(text[m[0]:m[1]], "#"),
start: int64(len([]rune(text[0:m[0]]))),
end: int64(len([]rune(text[0:m[1]])))},
)
}
return result
}