REGEXVAULTv2.0
Security/Secrets & Config
Verified Safe

Database Connection String with Credentials Regex for Go

/^(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 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

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

package validation

import "regexp"

var databaseConnectionStringWithCredentialsRe = regexp.MustCompile(`^(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|mssql|sqlserver|mariadb|oracle):\/\/([^:]+):([^@]+)@([^/?]+)(?:\/([^?]+))?(?:\?(.+))?$`)

func ValidateDatabaseConnectionStringWithCredentials(s string) bool {
    return databaseConnectionStringWithCredentialsRe.MatchString(s)
}

// Example
// fmt.Println(ValidateDatabaseConnectionStringWithCredentials("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 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

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