Environment Variable Secret Pattern (.env file) Regex for Go
/^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\r\n#]{8,})$/mWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching environment variable secret pattern (.env file), ported and verified for Go. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.
Go Implementation
// Environment Variable Secret Pattern (.env file)
// ReDoS-safe | RegexVault — Security > Secrets & Config
package validation
import "regexp"
var environmentVariableSecretPatternEnvFileRe = regexp.MustCompile(`^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\r\n#]{8,})$`)
func ValidateEnvironmentVariableSecretPatternEnvFile(s string) bool {
return environmentVariableSecretPatternEnvFileRe.MatchString(s)
}
// Example
// fmt.Println(ValidateEnvironmentVariableSecretPatternEnvFile("DATABASE_PASSWORD=mySecretPassword123")) // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
DATABASE_PASSWORD=mySecretPassword123 | PORT=3000 |
STRIPE_SECRET_KEY=sk_live_4eC39HqLyjWD | NODE_ENV=production |
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG | # PASSWORD_COMMENT=ignored |
| — | SHORT=ab |
When to use this pattern
This pattern is drawn from the Security > Secrets & Config category and carries a ReDoS-safe certification. That matters for Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Even if .env is in .gitignore, it may be committed before the .gitignore was added, or in a squashed commit. Use git log -- .env to check history. Consider pre-commit hooks that refuse to commit .env files.
Technical Notes
.env files should never be committed to version control. Use .gitignore to exclude .env files. The pattern uses multiline mode to match line-by-line. Capture group 1=key name, group 2=value. Value must be at least 8 chars to reduce false positives.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern