-
Notifications
You must be signed in to change notification settings - Fork 7
/
filters.go
93 lines (71 loc) · 1.93 KB
/
filters.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
package handy
import (
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
var reDupSpaces = regexp.MustCompile(`\s+`)
// DedupSpaces removes duplicated spaces, tabs and newLine characters
// I.E: Replaces two tabs for one single tab
func DedupSpaces(s string) string {
if s == "" {
return ""
}
s = reDupSpaces.ReplaceAllString(s, " ")
return s
}
// CleanSpaces removes duplicated spaces, tabs and newLine characters and then trim string's both sides
func CleanSpaces(s string) string {
if s == "" {
return ""
}
return strings.TrimSpace(DedupSpaces(s))
}
// OnlyLetters returns only the letters from the given string, after strip all the rest ( numbers, spaces, etc. )
func OnlyLetters(sequence string) string {
if utf8.RuneCountInString(sequence) == 0 {
return ""
}
var letters []rune
for _, r := range sequence {
if unicode.IsLetter(r) {
letters = append(letters, r)
}
}
return string(letters)
}
// OnlyDigits returns only the numbers from the given string, after strip all the rest ( letters, spaces, etc. )
func OnlyDigits(sequence string) string {
if utf8.RuneCountInString(sequence) > 0 {
re, _ := regexp.Compile(`[\D]`)
sequence = re.ReplaceAllString(sequence, "")
}
return sequence
}
// OnlyLettersAndNumbers returns only the letters and numbers from the given string, after strip all the rest, like spaces and special symbols.
func OnlyLettersAndNumbers(sequence string) string {
if utf8.RuneCountInString(sequence) == 0 {
return ""
}
var alphanumeric []rune
for _, r := range sequence {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
alphanumeric = append(alphanumeric, r)
}
}
return string(alphanumeric)
}
// RemoveDigits returns the given string without digit/numeric runes
func RemoveDigits(sequence string) string {
if utf8.RuneCountInString(sequence) == 0 {
return ""
}
var rs []rune
for _, r := range sequence {
if !unicode.IsDigit(r) {
rs = append(rs, r)
}
}
return string(rs)
}