Python (re)

MongoDB Connection URI in PY

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

Try it in the PY tester →

Pattern

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

Python (re) code

pyPython
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+.

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)