mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-15 10:12:29 +08:00
feat: add RemoveWhiteSpace
This commit is contained in:
@@ -5,6 +5,7 @@ package strutil
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode"
|
"unicode"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
@@ -552,3 +553,22 @@ func ContainsAny(str string, substrs []string) bool {
|
|||||||
|
|
||||||
return false
|
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.
|
||||||
|
// Play: todo
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -619,3 +619,17 @@ func ExampleContainsAny() {
|
|||||||
// true
|
// true
|
||||||
// false
|
// false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ExampleRemoveWhiteSpace() {
|
||||||
|
str := " hello \r\n \t world"
|
||||||
|
|
||||||
|
result1 := RemoveWhiteSpace(str, true)
|
||||||
|
result2 := RemoveWhiteSpace(str, false)
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// helloworld
|
||||||
|
// hello world
|
||||||
|
}
|
||||||
|
|||||||
@@ -466,3 +466,13 @@ func TestContainsAny(t *testing.T) {
|
|||||||
assert.Equal(true, ContainsAny("hello world", []string{"hello", "abc"}))
|
assert.Equal(true, ContainsAny("hello world", []string{"hello", "abc"}))
|
||||||
assert.Equal(false, ContainsAny("hello world", []string{"123", "abc"}))
|
assert.Equal(false, ContainsAny("hello world", []string{"123", "abc"}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRemoveWhiteSpace(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestRemoveWhiteSpace")
|
||||||
|
|
||||||
|
str := " hello \r\n \t world"
|
||||||
|
|
||||||
|
assert.Equal("", RemoveWhiteSpace("", true))
|
||||||
|
assert.Equal("helloworld", RemoveWhiteSpace(str, true))
|
||||||
|
assert.Equal("hello world", RemoveWhiteSpace(str, false))
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user