MongoDB ObjectId in PY
Match MongoDB ObjectId values — 24-character hexadecimal strings.
Try it in the PY tester →Pattern
regexPY
\b[0-9a-fA-F]{24}\b (flags: g)Python (re) code
pyPython
import re
pattern = re.compile(r"\b[0-9a-fA-F]{24}\b")
input_text = "507f1f77bcf86cd799439011"
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
Word-bounded exactly 24 hex digits. Case-insensitive character class covers both upper and lower case forms produced by different drivers.
Examples
Input
507f1f77bcf86cd799439011Matches
507f1f77bcf86cd799439011
Input
id: 5f8d0d55b54764421b7156c4Matches
5f8d0d55b54764421b7156c4
Input
not an objectidNo match
—