Skip to content

Commit

Permalink
feat: Add Regex cleaned string
Browse files Browse the repository at this point in the history
* A string that won't influence regex matching

Signed-off-by: AlexNg <contact@ngjx.org>
  • Loading branch information
caffeine-addictt committed Sep 1, 2024
1 parent 5c283fe commit c92e9b3
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 1 deletion.
20 changes: 19 additions & 1 deletion cmd/utils/string.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package utils

import "strings"
import (
"strings"
"unicode"
)

// StringStartsWith returns true if the given string
// starts with the given string look, or if they start similarily.
Expand All @@ -24,6 +27,21 @@ func EscapeTermString(s string) string {
return CleanString(s, '|', '&', ';', '`', '$')
}

// Invokes CleanString to prevent regex
func CleanStringNoRegex(s string) string {
var builder strings.Builder
builder.Grow(len(s)) // Optimize for the expected size to reduce reallocations.

for _, r := range s {
// Filter out any non-alphanumeric and non-space characters.
if unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.IsSpace(r) {
builder.WriteRune(r)
}
}

return builder.String()
}

// Escapes the given string from common escape sequences
// in 0(n) time, no regex.
//
Expand Down
58 changes: 58 additions & 0 deletions cmd/utils/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,64 @@ func TestCleaningString(t *testing.T) {
}
}

func TestCleanStringNoRegex(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "Alphanumeric string",
input: "Hello123",
expected: "Hello123",
},
{
name: "String with spaces",
input: "Hello World 123",
expected: "Hello World 123",
},
{
name: "String with special characters",
input: "Hello@World!123#",
expected: "HelloWorld123",
},
{
name: "String with unicode characters",
input: "こんにちは世界123",
expected: "こんにちは世界123",
},
{
name: "String with mixed valid and invalid characters",
input: "Hello, World! #123",
expected: "Hello World 123",
},
{
name: "Empty string",
input: "",
expected: "",
},
{
name: "String with only special characters",
input: "@#$%^&*()",
expected: "",
},
{
name: "String with leading and trailing spaces",
input: " Hello World ",
expected: " Hello World ",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := utils.CleanStringNoRegex(tt.input)
if result != tt.expected {
t.Errorf("CleanStringNoRegex(%q) = %q; expected %q", tt.input, result, tt.expected)
}
})
}
}

func BenchmarkStringStartsWith(b *testing.B) {
cases := []struct {
prefix string
Expand Down

0 comments on commit c92e9b3

Please sign in to comment.