Go (RE2)

Generic Connection String (URL Form) in GO

Parse generic URL-form connection strings: `protocol://[user[:pass]@]host[:port][/database]`.

Try it in the GO tester →

Pattern

regexGO
([a-zA-Z][\w+\-.]*):\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/([^?\s]*))?   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`([a-zA-Z][\w+\-.]*):\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/([^?\s]*))?`)
	input := `postgres://admin:s3cret@db.example.com:5432/main`
	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

Group 1 captures the scheme (postgres, mysql, redis, mongodb, kafka, etc.). The optional auth section captures user and optional password. Group 4 is the host. Optional port and path captures follow. This is a working starting point for parsing many SaaS connection strings; for production use a real URL parser.

Examples

Input

postgres://admin:s3cret@db.example.com:5432/main

Matches

  • postgres://admin:s3cret@db.example.com:5432/main

Input

kafka://broker.internal:9092

Matches

  • kafka://broker.internal:9092

Input

no connection here

No match

Same pattern, other engines

← Back to Generic Connection String (URL Form) overview (all engines)