-
Notifications
You must be signed in to change notification settings - Fork 0
/
sedetector.go
54 lines (41 loc) · 1.06 KB
/
sedetector.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
package main
import (
"errors"
"regexp"
"strconv"
"strings"
)
type SeasonEpisodeDetector struct {
regexes []*regexp.Regexp
}
func NewSeasonEpisodeDetector() *SeasonEpisodeDetector {
detector := new(SeasonEpisodeDetector)
detector.regexes = []*regexp.Regexp{
regexp.MustCompile("(.*)s(?P<season>\\d+)(\\s*)e(?P<episode>\\d+)([^\\d]*)"),
regexp.MustCompile("([^\\d]*)(?P<season>\\d+)x(?P<episode>\\d+)([^\\d]*)")}
return detector
}
func (detector *SeasonEpisodeDetector) Detect(file string) (season, episode int, err error) {
for _, reg := range detector.regexes {
match := reg.FindStringSubmatch(strings.ToLower(file))
if match == nil {
continue
}
result := make(map[string]string)
for i, name := range reg.SubexpNames() {
if i != 0 {
result[name] = match[i]
}
}
season, e := strconv.Atoi(result["season"])
episode, e2 := strconv.Atoi(result["episode"])
if e != nil {
return 0, 0, e
}
if e2 != nil {
return 0, 0, e2
}
return season, episode, nil
}
return 0, 0, errors.New("Season/episode pattern not detected")
}