-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhitespace.go
42 lines (37 loc) · 849 Bytes
/
whitespace.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
package main
import (
"regexp"
"strings"
)
func removeWhitespace(input string, removeSpaces bool, removeTabs bool, removeCR bool, removeNewlines bool, removeEmptyLines bool) string {
pattern := ""
if removeSpaces {
pattern += " "
}
if removeTabs {
pattern += "\t"
}
if removeCR {
pattern += "\r"
}
if removeNewlines {
pattern += "\n"
}
// Replace specified whitespace characters
if pattern != "" {
re := regexp.MustCompile("[" + regexp.QuoteMeta(pattern) + "]")
input = re.ReplaceAllString(input, "")
}
// Remove empty lines if specified
if removeEmptyLines {
lines := strings.Split(input, "\n")
var nonEmptyLines []string
for _, line := range lines {
if strings.TrimSpace(line) != "" {
nonEmptyLines = append(nonEmptyLines, line)
}
}
input = strings.Join(nonEmptyLines, "\n")
}
return input
}