gabeno gabeno - 6 months ago 83
Javascript Question

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.

Answer

You can use following regular expression

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; IMHO, you should use /^[a-f\d]{24}$/i.

Comments