-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
71 lines (52 loc) · 1.16 KB
/
parser.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
package hashtag
import (
"log"
"regexp"
"strings"
)
const (
reHashTag = `#\w+`
)
type Parser struct {
re *regexp.Regexp
caseSensitive bool
}
func NewParser(caseSensitive bool) *Parser {
parser := &Parser{
caseSensitive: caseSensitive,
}
parser.re = regexp.MustCompile(reHashTag)
return parser
}
// Parse Parsing text for hashtags. If no hashtags were found, nil will be returned.
// Returns a map where hashtag is the key and value is the number uses of the hashtag in the text.
func (receiver *Parser) Parse(text string) map[string]int {
if len(text) == 0 {
return nil
}
text = strings.ReplaceAll(text, ` `, "\n")
log.Printf("t: `%s`", text)
log.Printf("found: %++v\n", receiver.re.FindAllStringSubmatch(text, -1))
found := receiver.re.FindAllString(text, -1)
log.Printf("found: %++v\n", found)
l := len(found)
if l == 0 {
return nil
}
result := make(map[string]int, l)
for _, s := range found {
if s[len(s)-1:] == "#" {
continue
}
key := strings.TrimSpace(s)[1:]
if !receiver.caseSensitive {
key = strings.ToLower(key)
}
log.Printf("key: `%s`", key)
result[key]++
}
if len(result) == 0 {
return nil
}
return result
}