From 6b05c20b0ae971d251234ad2b40e5dcb37214ebf Mon Sep 17 00:00:00 2001 From: Phillip Leonardo Date: Fri, 19 Jul 2024 10:36:45 +0700 Subject: [PATCH] Add extract alfanumeric with selected special characters (#4) * add extract alfanumeric with selected special characters * fix comment --- str/string.go | 15 +++++++++++++++ str/string_test.go | 13 +++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 str/string_test.go diff --git a/str/string.go b/str/string.go index f7cd610..c74765f 100644 --- a/str/string.go +++ b/str/string.go @@ -29,6 +29,21 @@ func ExtractAlfaNumericFromText(source string) string { return result.String() } +func ExtractAlfaNumericWithSelectedSpecialCharactersFromText(source string) string { + // allowed special characters are !"#$%&'()*+,-./ \[]\n + var result strings.Builder + for i := 0; i < len(source); i++ { + b := source[i] + if (32 <= b && b <= 57) || + (65 <= b && b <= 93) || + (97 <= b && b <= 122) || + b == 10 { + result.WriteByte(b) + } + } + return result.String() +} + func SplitOnNotEmpty(str string, delimiter string) []string { if strings.TrimSpace(str) != "" { var result []string diff --git a/str/string_test.go b/str/string_test.go new file mode 100644 index 0000000..89ed073 --- /dev/null +++ b/str/string_test.go @@ -0,0 +1,13 @@ +package str + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestExtractAlfaNumericWithSelectedSpecialCharactersFromText(t *testing.T) { + sourceText := "Ab9 \\!@#$%^&*_+-=\n" + validateText := "Ab9 \\!#$%&*+-\n" + filteredText := ExtractAlfaNumericWithSelectedSpecialCharactersFromText(sourceText) + assert.Equal(t, validateText, filteredText) +}