-
Notifications
You must be signed in to change notification settings - Fork 13
/
normalize.go
54 lines (41 loc) · 1.33 KB
/
normalize.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 util
import (
"regexp"
"strings"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
const (
separator = "-"
)
func NormalizeNameForCentral(str string) string {
if str == "" {
return ""
}
str = strings.Trim(str, " ") // remove leading and trailing blanks
// replace accented characters with their non-accented English character equivalents.
str = removeDiacritics(str)
str = regexp.MustCompile(`[ß]`).ReplaceAllString(str, "ss")
str = regexp.MustCompile(`[Øø]`).ReplaceAllString(str, "o")
str = regexp.MustCompile(`[Ææ]`).ReplaceAllString(str, "ae")
str = regexp.MustCompile(`[Œœ]`).ReplaceAllString(str, "oe")
// make string all lowercase
str = strings.ToLower(str)
// replace invalid characters with "-" and reduce to 1 "-" maximum
str = regexp.MustCompile(`[^a-z0-9-]`).ReplaceAllString(str, separator)
str = regexp.MustCompile(`[-]{2,}`).ReplaceAllString(str, separator)
// remove leading and trailing "-"
str = strings.Trim(str, separator)
return str
}
type runesSet struct{}
func (s runesSet) Contains(r rune) bool {
return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
}
func removeDiacritics(input string) string {
t := transform.Chain(norm.NFD, runes.Remove(runesSet{}), norm.NFC)
result, _, _ := transform.String(t, input)
return result
}