Python (re)

PostgreSQL DSN in PY

Match PostgreSQL DSN connection strings (`postgres://` or `postgresql://`), capturing the standard URL components.

Try it in the PY tester →

Pattern

regexPY
postgres(?:ql)?:\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/(\w+))?(?:\?\S*)?   (flags: g)

Python (re) code

pyPython
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+.

How the pattern works

postgres(?:ql)? matches both the short and long scheme spellings. The optional auth group, host, port, and database name follow the standard URL form. (?:\?\S*)? optionally matches query parameters (sslmode, application_name, pool_max_conns, etc.).

Examples

Input

DATABASE_URL=postgresql://app:s3cret@db.neon.tech:5432/main?sslmode=require

Matches

  • postgresql://app:s3cret@db.neon.tech:5432/main?sslmode=require

Input

postgres://localhost/dev

Matches

  • postgres://localhost/dev

Input

no dsn here

No match

Same pattern, other engines

← Back to PostgreSQL DSN overview (all engines)