Regex for MongoDB ObjectID

Solution 1:

You can use following regular expression but it will not quite work

checkForHexRegExp = /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i

Example:

> checkForHexRegExp.test("112345679065574883030833")
false
> checkForHexRegExp.test("FFFFFFFFFFFFFFFFFFFFFFFF")
false
> checkForHexRegExp.test("45cbc4a0e4123f6920000002")
true

But, as I commented, 112345679065574883030833, FFFFFFFFFFFFFFFFFFFFFFFF are also valid hexadecimal representations.

You should use /^[a-f\d]{24}$/i because it passes all the above tests

Solution 2:

I need a regex that will only match mongodb ObjectIDs

If you need that, you will have to specify exactly what makes up a mongodb ObjectID, so that we can create the appropriate regex string for it.


This should technically work in js:

var myregexp = /^[0-9a-fA-F]{24}$/;
subject = "112345679065574883030833";

if (subject.match(myregexp)) {
    // Successful match
} else {
    // Match attempt failed
}

Solution 3:

Technically, all examples in the question potentially could be valid ObjectIds. If you have to add some additional verification and that regexp is not enough, then my suggestion is to check if the first 4 bytes are a valid timestamp. You can even verify that ObjectId has been generated during a certain period of time (e.g. since your project has been started or so). See ObjectId documentation for details.

If there's another timestamp field in an object, then it's also possible to make sure that both times are really close.

Just for the reference, in MongoDB shell ObjectId::getTimestamp() method can be used to extract a timestamp from ObjectId.