54

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.

Community
  • 1
  • 1
gmajivu
  • 1,272
  • 2
  • 13
  • 21

5 Answers5

108

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

John Culviner
  • 22,235
  • 6
  • 55
  • 51
falsetru
  • 357,413
  • 63
  • 732
  • 636
22

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
}
Vasili Syrakis
  • 9,321
  • 1
  • 39
  • 56
5

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.

Oleg Shparber
  • 2,732
  • 1
  • 18
  • 19
3

I would do something like this

function validateObjectId(id)
{
    var bool=false; 
    if(id.length==24) bool=/[a-f]+/.test(id);
    return bool;
}


> validateObjectId("112345679065574883030833")
  false
> validateObjectId("FFFFFFFFFFFFFFFFFFFFFFFF")
  false
> validateObjectId("45cbc4a0e4123f6920000002")
  true
> validateObjectId("45cbc4a0e4123f6920")
  false
Amarnath Krishnan
  • 1,253
  • 1
  • 9
  • 12
0

For those who was looking just for hex checking the string:

s := "5fa0ef460c2056137465a39b"
if _, err := hex.DecodeString(s); err == nil {
    fmt.Println("ok")
}
Dmitriy Botov
  • 2,623
  • 1
  • 15
  • 12