-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextract.go
103 lines (93 loc) · 2.44 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// This file is copied from: https://github.com/mattn/bsky/blob/05cbf0a2797313b779950ee4afaa9adcf92c58f3/extract.go
package main
import (
"regexp"
"strings"
)
const (
urlPattern = `https?://[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)]+`
mentionPattern = `@[a-zA-Z0-9.]+`
tagPattern = `\B#\S+`
)
var (
urlRe = regexp.MustCompile(urlPattern)
mentionRe = regexp.MustCompile(mentionPattern)
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 extractLinksBytes(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(text[0:m[0]])),
end: int64(len(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 extractMentionsBytes(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(text[0:m[0]])),
end: int64(len(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
}
func extractTagsBytes(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(text[0:m[0]])),
end: int64(len(text[0:m[1]]))},
)
}
return result
}