Regexp Raw String
ID |
go.regexp_raw_string |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Go |
Tags |
best-practice, readability |
Description
Reports regexp.MustCompile / regexp.Compile calls whose pattern is given as a
double-quoted (interpreted) string literal containing backslash escapes. The idiomatic form
is a backtick raw string literal.
Rationale
In a Go interpreted string, the backslash starts an escape sequence, so every regex
metacharacter must be double-escaped — "\\d+" for the pattern \d+. This is noisy and a
frequent source of bugs when an escape is forgotten or mistyped. A backtick raw string takes
its bytes verbatim, so the pattern reads exactly as it matches.
regexp.MustCompile("\\d+") // FLAW — double-escaped interpreted string
regexp.MustCompile(`\d+`) // OK — raw string
regexp.MustCompile("plain") // OK — no escapes