expr_ref_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2021-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ast
  15. import (
  16. "regexp"
  17. "strings"
  18. "testing"
  19. )
  20. func compileByReplaceAll(likestr string) (*regexp.Regexp, error) {
  21. likestr = strings.ReplaceAll(strings.ReplaceAll(likestr, `\%`, `!@#`), `\_`, `!@$`)
  22. regstr := strings.ReplaceAll(strings.ReplaceAll(likestr, "%", ".*"), "_", ".")
  23. regstr = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(regstr, `!@$`, `\_`), `!@#`, `\%`), `\`, `\\`)
  24. return regexp.Compile("^" + regstr + "$")
  25. }
  26. func TestLikePatternCompile(t *testing.T) {
  27. l := LikePattern{}
  28. tests := []string{
  29. `%`, `_`, `\`, `\\`, `\%`, `\_`, `\\%`, `\\_`, `%\\%`, `%\\_`, `%\\%\\%`, `%\\%\\_`, `%\\%\\%`, `%\\%\\_`,
  30. }
  31. for i, test := range tests {
  32. expect, err := compileByReplaceAll(test)
  33. if err != nil {
  34. panic(err)
  35. }
  36. actual, err := l.Compile(test)
  37. if err != nil {
  38. panic(err)
  39. }
  40. if expect.String() != actual.String() {
  41. t.Errorf("%d. \nexpect: %s, actual: %s\n", i, expect, actual)
  42. }
  43. }
  44. }