1// Use of this source code is governed by a BSD-style
2// license that can be found in the LICENSE file.
3
4// Package regexp implements a simple regular expression library.
5
6// QuoteMeta func is copied here to avoid linking the entire Regexp library.
7
8package rubex
9
10func special(c int) bool {
11 for _, r := range `\.+*?()|[]^$` {
12 if c == int(r) {
13 return true
14 }
15 }
16 return false
17}
18
19// QuoteMeta returns a string that quotes all regular expression metacharacters
20// inside the argument text; the returned string is a regular expression matching
21// the literal text. For example, QuoteMeta(`[foo]`) returns `\[foo\]`.
22func QuoteMeta(s string) string {
23 b := make([]byte, 2*len(s))
24
25 // A byte loop is correct because all metacharacters are ASCII.
26 j := 0
27 for i := 0; i < len(s); i++ {
28 if special(int(s[i])) {
29 b[j] = '\\'
30 j++
31 }
32 b[j] = s[i]
33 j++
34 }
35 return string(b[0:j])
36}