REGEXVAULTv2.0
Security/Secrets & Config
Verified Safe

Database Connection String with Credentials Regex for Python

/^(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|mssql|sqlserver|mariadb|oracle):\/\/([^:]+):([^@]+)@([^/?]+)(?:\/([^?]+))?(?:\?(.+))?$/i

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching database connection string with credentials, ported and verified for Python. 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 Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.

Python Implementation

Python
# Database Connection String with Credentials
# ReDoS-safe | RegexVault — Security > Secrets & Config

import re

database_connection_string_with_credentials_pattern = re.compile(r'^(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|mssql|sqlserver|mariadb|oracle):\/\/([^:]+):([^@]+)@([^/?]+)(?:\/([^?]+))?(?:\?(.+))?$')

def validate_database_connection_string_with_credentials(value: str) -> bool:
    return bool(database_connection_string_with_credentials_pattern.fullmatch(value))

# Example
print(validate_database_connection_string_with_credentials("postgresql://user:password@localhost:5432/mydb"))  # True

Test Cases

Matches (Valid)
Rejects (Invalid)
postgresql://user:password@localhost:5432/mydbpostgresql://localhost:5432/mydb
mysql://root:secret@db.example.com/appftp://user:pass@host/path
mongodb+srv://admin:P%40ssw0rd@cluster.example.net/prodpostgresql://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 Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. 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