| 32 | |
| 33 | var regex strings.Builder |
| 34 | regex.WriteString("^") |
| 35 | |
| 36 | for i := 0; i < len(pattern); i++ { |
| 37 | c := pattern[i] |
| 38 | switch c { |
| 39 | case '*': |
| 40 | regex.WriteString(".*") |
| 41 | case '?': |
| 42 | regex.WriteString(".") |
| 43 | case '[': |
| 44 | // A character class is only a class when it is closed and non-empty; |
| 45 | // otherwise Redis matches the bracket literally. |
| 46 | closing := -1 |
| 47 | for j := i + 1; j < len(pattern); j++ { |
| 48 | if pattern[j] == ']' { |
| 49 | closing = j |
| 50 | break |
| 51 | } |
| 52 | } |
| 53 | if closing <= i+1 { |
| 54 | regex.WriteString(`\[`) |
| 55 | continue |
| 56 | } |
| 57 | regex.WriteString("[") |
| 58 | for j := i + 1; j < closing; j++ { |
| 59 | regex.WriteByte(pattern[j]) |
| 60 | } |
| 61 | regex.WriteString("]") |
| 62 | i = closing |
| 63 | case '\\': |
| 64 | // Escape the next character; a trailing backslash is a literal one. |
| 65 | if i+1 < len(pattern) { |
| 66 | regex.WriteString(regexp.QuoteMeta(string(pattern[i+1]))) |
| 67 | i++ |
| 68 | } else { |
| 69 | regex.WriteString(`\\`) |
| 70 | } |
| 71 | default: |
| 72 | if isMetaChar(c) { |
| 73 | regex.WriteString("\\") |