REGEXVAULTv2.0
Security/Secrets & Config
Verified Safe

Environment Variable Secret Pattern (.env file) Regex for Java

/^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\r\n#]{8,})$/m

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching environment variable secret pattern (.env file), ported and verified for Java. 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 Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.

Java Implementation

Java
// Environment Variable Secret Pattern (.env file)
// ReDoS-safe | RegexVault — Security > Secrets & Config

import java.util.regex.Pattern;

public class EnvironmentVariableSecretPatternEnvFileValidator {
    private static final Pattern PATTERN =
        Pattern.compile("^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\\r\\n#]{8,})$");

    public static boolean validate(String input) {
        return PATTERN.matcher(input).matches();
    }

    // Example
    public static void main(String[] args) {
        System.out.println(validate("DATABASE_PASSWORD=mySecretPassword123")); // true
    }
}

Test Cases

Matches (Valid)
Rejects (Invalid)
DATABASE_PASSWORD=mySecretPassword123PORT=3000
STRIPE_SECRET_KEY=sk_live_4eC39HqLyjWDNODE_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 Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. 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