PostgreSQL DSN in GO
Match PostgreSQL DSN connection strings (`postgres://` or `postgresql://`), capturing the standard URL components.
Try it in the GO tester →Pattern
regexGO
postgres(?:ql)?:\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/(\w+))?(?:\?\S*)? (flags: g)Go (RE2) code
goGo
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.
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=requireMatches
postgresql://app:s3cret@db.neon.tech:5432/main?sslmode=require
Input
postgres://localhost/devMatches
postgres://localhost/dev
Input
no dsn hereNo match
—