Developer

Regular expression

/^[0-9a-fA-F]{24}$/

Pattern breakdown

PartMeaning
Anchor or contextUse anchors when you need whole-string validation.
Main tokenThe core token sequence describes the accepted text shape.
Character classCharacter classes limit which characters are valid.
QuantifierQuantifiers control how many characters or groups are accepted.
FlagsUse language-specific flags such as i, m, or u only when needed.

Should match

  • 64f1a2b3c4d5e6f789012345

Should not match

  • not-object-id
  • not matching sample
  • 64f1a2b3c4d5e6f789012345 invalid
  • not-object-id64f1a2b3c4d5e6f789012345

Test cases

InputExpectedWhy it matters
64f1a2b3c4d5e6f789012345MatchRepresentative valid input for this pattern.
not-object-idNo matchCommon invalid or boundary input.
(empty string)No matchCommon invalid or boundary input.
not matching sampleNo matchCommon invalid or boundary input.
64f1a2b3c4d5e6f789012345 invalidNo matchCommon invalid or boundary input.
not-object-id64f1a2b3c4d5e6f789012345No matchCommon invalid or boundary input.

JavaScript

const re = /^[0-9a-fA-F]{24}$/;
re.test(input);

Python

import re
bool(re.search(r"^[0-9a-fA-F]{24}$", text))

PHP

$ok = preg_match('/^[0-9a-fA-F]{24}$/', $value) === 1;

Java

Pattern pattern = Pattern.compile("^[0-9a-fA-F]{24}$");
pattern.matcher(value).find();

Go

re := regexp.MustCompile(`^[0-9a-fA-F]{24}$`)
ok := re.MatchString(value)

Notes and production use

MongoDB ObjectId regex is useful as a practical starting point. Test it against your real input, avoid using it as the only security control, and prefer a parser when the format has complex grammar.

Performance tip: avoid running complex regular expressions repeatedly on very large untrusted strings without limits. Prefer anchored validation patterns, cap input length before matching, and use a parser when the target format has nested grammar.