JavaScript / ECMAScript

PostgreSQL DSN in JS

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

Try it in the JS tester →

Pattern

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

JavaScript / ECMAScript code

jsJavaScript
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).

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)