Go (RE2)

MongoDB Connection URI in GO

Match MongoDB connection URIs in both standard `mongodb://` and SRV `mongodb+srv://` formats.

Try it in the GO tester →

Pattern

regexGO
mongodb(?:\+srv)?:\/\/(?:[^:@\s]+(?::[^@\s]*)?@)?[^\/?\s]+(?:\/[^?\s]*)?(?:\?\S*)?   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`mongodb(?:\+srv)?:\/\/(?:[^:@\s]+(?::[^@\s]*)?@)?[^\/?\s]+(?:\/[^?\s]*)?(?:\?\S*)?`)
	input := `Conn: mongodb://user:pass@cluster0.mongodb.net:27017/mydb`
	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

mongodb(?:\+srv)?:\/\/ matches either scheme. (?:[^:@\s]+(?::[^@\s]*)?@)? optionally matches user[:password]@. [^\/?\s]+ matches the host (potentially comma-separated for replica sets, though this regex captures only up to the first / or ?). (?:\/[^?\s]*)? optionally matches the database path. (?:\?\S*)? optionally matches query parameters.

Examples

Input

Conn: mongodb://user:pass@cluster0.mongodb.net:27017/mydb

Matches

  • mongodb://user:pass@cluster0.mongodb.net:27017/mydb

Input

mongodb+srv://admin@prod.example.com/main?retryWrites=true

Matches

  • mongodb+srv://admin@prod.example.com/main?retryWrites=true

Input

no connection here

No match

Same pattern, other engines

← Back to MongoDB Connection URI overview (all engines)