Use raw strings to describe regexes, avoids double escaping

This commit is contained in:
Jakob Borg 2015-09-02 22:19:45 +02:00
parent fea0ae7f2f
commit 2581e56503

View File

@ -27,43 +27,43 @@ func Convert(pattern string, flags int) (*regexp.Regexp, error) {
flags |= NoEscape | CaseFold flags |= NoEscape | CaseFold
pattern = filepath.FromSlash(pattern) pattern = filepath.FromSlash(pattern)
if flags&PathName != 0 { if flags&PathName != 0 {
any = "[^\\\\]" any = `[^\\]`
} }
case "darwin": case "darwin":
flags |= CaseFold flags |= CaseFold
fallthrough fallthrough
default: default:
if flags&PathName != 0 { if flags&PathName != 0 {
any = "[^/]" any = `[^/]`
} }
} }
if flags&NoEscape != 0 { if flags&NoEscape != 0 {
pattern = strings.Replace(pattern, "\\", "\\\\", -1) pattern = strings.Replace(pattern, `\`, `\\`, -1)
} else { } else {
pattern = strings.Replace(pattern, "\\*", "[:escapedstar:]", -1) pattern = strings.Replace(pattern, `\*`, "[:escapedstar:]", -1)
pattern = strings.Replace(pattern, "\\?", "[:escapedques:]", -1) pattern = strings.Replace(pattern, `\?`, "[:escapedques:]", -1)
pattern = strings.Replace(pattern, "\\.", "[:escapeddot:]", -1) pattern = strings.Replace(pattern, `\.`, "[:escapeddot:]", -1)
} }
// Characters that are special in regexps but not in glob, must be // Characters that are special in regexps but not in glob, must be
// escaped. // escaped.
for _, char := range []string{".", "+", "$", "^", "(", ")", "|"} { for _, char := range []string{`.`, `+`, `$`, `^`, `(`, `)`, `|`} {
pattern = strings.Replace(pattern, char, "\\"+char, -1) pattern = strings.Replace(pattern, char, `\`+char, -1)
} }
pattern = strings.Replace(pattern, "**", "[:doublestar:]", -1) pattern = strings.Replace(pattern, `**`, `[:doublestar:]`, -1)
pattern = strings.Replace(pattern, "*", any+"*", -1) pattern = strings.Replace(pattern, `*`, any+`*`, -1)
pattern = strings.Replace(pattern, "[:doublestar:]", ".*", -1) pattern = strings.Replace(pattern, `[:doublestar:]`, `.*`, -1)
pattern = strings.Replace(pattern, "?", any, -1) pattern = strings.Replace(pattern, `?`, any, -1)
pattern = strings.Replace(pattern, "[:escapedstar:]", "\\*", -1) pattern = strings.Replace(pattern, `[:escapedstar:]`, `\*`, -1)
pattern = strings.Replace(pattern, "[:escapedques:]", "\\?", -1) pattern = strings.Replace(pattern, `[:escapedques:]`, `\?`, -1)
pattern = strings.Replace(pattern, "[:escapeddot:]", "\\.", -1) pattern = strings.Replace(pattern, `[:escapeddot:]`, `\.`, -1)
pattern = "^" + pattern + "$" pattern = `^` + pattern + `$`
if flags&CaseFold != 0 { if flags&CaseFold != 0 {
pattern = "(?i)" + pattern pattern = `(?i)` + pattern
} }
return regexp.Compile(pattern) return regexp.Compile(pattern)
} }