Database Connection String with Credentials Regex for Java
/^(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|mssql|sqlserver|mariadb|oracle):\/\/([^:]+):([^@]+)@([^/?]+)(?:\/([^?]+))?(?:\?(.+))?$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching database connection string with credentials, 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
// Database Connection String with Credentials
// ReDoS-safe | RegexVault — Security > Secrets & Config
import java.util.regex.Pattern;
public class DatabaseConnectionStringWithCredentialsValidator {
private static final Pattern PATTERN =
Pattern.compile("^(postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|mssql|sqlserver|mariadb|oracle):\\/\\/([^:]+):([^@]+)@([^/?]+)(?:\\/([^?]+))?(?:\\?(.+))?$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("postgresql://user:password@localhost:5432/mydb")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
postgresql://user:password@localhost:5432/mydb | postgresql://localhost:5432/mydb |
mysql://root:secret@db.example.com/app | ftp://user:pass@host/path |
mongodb+srv://admin:P%40ssw0rd@cluster.example.net/prod | postgresql://user:@localhost/db |
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
Connection strings in Heroku, Render, and Railway configs are often set as environment variables but may be hardcoded in old codebases or appear in error messages when logged. Never log connection strings.
Technical Notes
Capture groups: 1=scheme, 2=username, 3=password, 4=host:port, 5=database, 6=query params. Passwords may be URL-encoded (e.g., P%40ssw0rd). Extract and rotate any credentials found in this format in code or config files.
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