MongoDB Connection URI
Match MongoDB connection URIs in both standard `mongodb://` and SRV `mongodb+srv://` formats.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("mongodb(?:\\+srv)?:\\/\\/(?:[^:@\\s]+(?::[^@\\s]*)?@)?[^\\/?\\s]+(?:\\/[^?\\s]*)?(?:\\?\\S*)?", "g");
const input = "Conn: mongodb://user:pass@cluster0.mongodb.net:27017/mydb";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"mongodb(?:\+srv)?:\/\/(?:[^:@\s]+(?::[^@\s]*)?@)?[^\/?\s]+(?:\/[^?\s]*)?(?:\?\S*)?")
input_text = "Conn: mongodb://user:pass@cluster0.mongodb.net:27017/mydb"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
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.
Pattern
mongodb(?:\+srv)?:\/\/(?:[^:@\s]+(?::[^@\s]*)?@)?[^\/?\s]+(?:\/[^?\s]*)?(?:\?\S*)? (flags: g)Raw source: mongodb(?:\+srv)?:\/\/(?:[^:@\s]+(?::[^@\s]*)?@)?[^\/?\s]+(?:\/[^?\s]*)?(?:\?\S*)?
How it works
Examples
Input
Conn: mongodb://user:pass@cluster0.mongodb.net:27017/mydbMatches
mongodb://user:pass@cluster0.mongodb.net:27017/mydb
Input
mongodb+srv://admin@prod.example.com/main?retryWrites=trueMatches
mongodb+srv://admin@prod.example.com/main?retryWrites=true
Input
no connection hereNo match
—Common use cases
- •Linting config files for connection strings
- •Detecting committed credentials in PRs
- •Migration scripts that need to parse URIs
- •Observability — extracting cluster names from logs
Related patterns
JDBC Connection URL
NetworkingMatch JDBC connection URLs in the standard `jdbc:driver://host[:port][/database]` form.
Redis Connection URL
NetworkingMatch Redis connection URLs in both `redis://` and `rediss://` (TLS) forms, capturing user, password, host, port, and DB index.
Generic Connection String (URL Form)
NetworkingParse generic URL-form connection strings: `protocol://[user[:pass]@]host[:port][/database]`.
PostgreSQL DSN
NetworkingMatch PostgreSQL DSN connection strings (`postgres://` or `postgresql://`), capturing the standard URL components.