1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-07 06:02:27 +08:00

feat: add RemoveWhiteSpace

This commit is contained in:
dudaodong
2023-06-13 15:06:27 +08:00
parent 275abcc8c2
commit 1e5b69e9bf
4 changed files with 268 additions and 170 deletions

View File

@@ -6,6 +6,7 @@ package strutil
import (
"reflect"
"regexp"
"strings"
"unicode"
"unicode/utf8"
@@ -503,3 +504,21 @@ func ContainsAny(str string, substrs []string) bool {
return false
}
var (
whitespaceRegexMatcher *regexp.Regexp = regexp.MustCompile(`\s`)
mutiWhitespaceRegexMatcher *regexp.Regexp = regexp.MustCompile(`[[:space:]]{2,}|[\s\p{Zs}]{2,}`)
)
// RemoveWhiteSpace remove whitespace characters from a string.
// when set repalceAll is true removes all whitespace, false only replaces consecutive whitespace characters with one space.
func RemoveWhiteSpace(str string, repalceAll bool) string {
if repalceAll && str != "" {
return strings.Join(strings.Fields(str), "")
} else if str != "" {
str = mutiWhitespaceRegexMatcher.ReplaceAllString(str, " ")
str = whitespaceRegexMatcher.ReplaceAllString(str, " ")
}
return strings.TrimSpace(str)
}