PostgreSQL DSN
Match PostgreSQL DSN connection strings (`postgres://` or `postgresql://`), capturing the standard URL components.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("postgres(?:ql)?:\\/\\/(?:([^:@\\s]+)(?::([^@\\s]*))?@)?([^:\\/\\s]+)(?::(\\d+))?(?:\\/(\\w+))?(?:\\?\\S*)?", "g");
const input = "DATABASE_URL=postgresql://app:s3cret@db.neon.tech:5432/main?sslmode=require";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"postgres(?:ql)?:\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/(\w+))?(?:\?\S*)?")
input_text = "DATABASE_URL=postgresql://app:s3cret@db.neon.tech:5432/main?sslmode=require"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`postgres(?:ql)?:\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/(\w+))?(?:\?\S*)?`)
input := `DATABASE_URL=postgresql://app:s3cret@db.neon.tech:5432/main?sslmode=require`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
postgres(?:ql)?:\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/(\w+))?(?:\?\S*)? (flags: g)Raw source: postgres(?:ql)?:\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/(\w+))?(?:\?\S*)?
How it works
Examples
Input
DATABASE_URL=postgresql://app:s3cret@db.neon.tech:5432/main?sslmode=requireMatches
postgresql://app:s3cret@db.neon.tech:5432/main?sslmode=require
Input
postgres://localhost/devMatches
postgres://localhost/dev
Input
no dsn hereNo match
—Common use cases
- •Linting .env files for committed credentials
- •Migration tooling that splits DSNs into parts
- •Multi-tenant routing by database name
- •Observability tags from connection metadata
Related patterns
Generic Connection String (URL Form)
NetworkingParse generic URL-form connection strings: `protocol://[user[:pass]@]host[:port][/database]`.
JDBC Connection URL
NetworkingMatch JDBC connection URLs in the standard `jdbc:driver://host[:port][/database]` form.
MongoDB Connection URI
NetworkingMatch MongoDB connection URIs in both standard `mongodb://` and SRV `mongodb+srv://` formats.
Redis Connection URL
NetworkingMatch Redis connection URLs in both `redis://` and `rediss://` (TLS) forms, capturing user, password, host, port, and DB index.