Skip to content

Commit

Permalink
add KStr.Quotemeta
Browse files Browse the repository at this point in the history
  • Loading branch information
kakuilan committed May 16, 2021
1 parent bc53aa5 commit d82eb01
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
13 changes: 13 additions & 0 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -1396,3 +1396,16 @@ func (ks *LkkString) UnSerialize(data []byte, register ...interface{}) (val inte
err = dec.Decode(&val)
return
}

// Quotemeta 转义元字符集,包括 . \ + * ? [ ^ ] ( $ )等.
func (ks *LkkString) Quotemeta(str string) string {
var buf bytes.Buffer
for _, char := range str {
switch char {
case '.', '+', '\\', '(', '$', ')', '[', '^', ']', '*', '?':
buf.WriteRune('\\')
}
buf.WriteRune(char)
}
return buf.String()
}
17 changes: 17 additions & 0 deletions string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2500,3 +2500,20 @@ func BenchmarkString_UnSerialize(b *testing.B) {
_, _ = KStr.UnSerialize(str)
}
}

func TestString_Quotemeta(t *testing.T) {
var res string

res = KStr.Quotemeta("")
assert.Empty(t, res)

res = KStr.Quotemeta(tesStr35)
assert.Contains(t, res, '\\')
}

func BenchmarkString_Quotemeta(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
KStr.Quotemeta(tesStr35)
}
}
1 change: 1 addition & 0 deletions testdata.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ var tesStr31 = "\014\012\011\013 abc \015"
var tesStr32 = "\f\n\t\v\r\f"
var tesStr33 = "x\n\t\t\t\t"
var tesStr34 = "\f\n\t \n\n\n \v\r\f"
var tesStr35 = "Hi jac. $a=3*5, (can you hear me?)"

//中文名
var tesChineseName1 = "李四"
Expand Down

0 comments on commit d82eb01

Please sign in to comment.