Q:

Regex for MongoDB ObjectID

With reference to this SO question, I have a scenario where I only need to match a hex string with a-f included. All else should not match. Example:
checkForHexRegExp.test("112345679065574883030833"); // => false
checkForHexRegExp.test("FFFFFFFFFFFFFFFFFFFFFFFF"); // => false
checkForHexRegExp.test("45cbc4a0e4123f6920000002"); // => true

My use case is that I am working with a set of hex strings and would like to only validate as true those that are mongodb objectIDs.

A:

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

A:

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
}

A:

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.

