Valid Regular Expression
ID |
go.valid_regular_expression |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious |
Description
Reports a regexp.Compile / regexp.MustCompile call whose pattern is a string literal that
contains a clear structural syntax error — an unbalanced group or an unclosed character class.
A bad pattern makes MustCompile panic at startup and Compile return an error, so the
expression never runs.
Rationale
A malformed pattern in a literal is a typo that the compiler cannot catch; it surfaces only when
the program starts (a MustCompile panic) or when the error from Compile is checked. Only a
constant pattern can be validated statically. The pattern is checked with a best-effort proxy, and
to avoid flagging anything that is valid in Go’s RE2 syntax but rejected by the proxy, only the two
unambiguous errors shared by both — an unmatched parenthesis and an unclosed character class — are
reported.
regexp.MustCompile("a(b") // FLAW — unbalanced parenthesis
regexp.Compile("[a-z") // FLAW — unclosed character class
regexp.MustCompile("valid[a-z]+") // OK
regexp.MustCompile(dynamic) // OK — non-constant pattern