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.
Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.
An ObjectId in MongoDB is a 12-byte BSON type. In the 12-byte structure, the first 4 bytes of the ObjectId represent the time in seconds since the UNIX epoch. The next 3 bytes of the ObjectId represent the machine identifier. The next 2 bytes of the ObjectId represent the process ID.
You should NOT convert the ObjectId in the database to a string, and then compare it to another string. If you'd do this, MongoDB cannot use the _id index and it'll have to scan all the documents, resulting in poor query performance. Show activity on this post. Don't.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With