1

In other posts they explain how to match a MongoDB object id through a regex. I am looking the opposite: given a string, a regex that returns positive if it is not a valid mongo object id. In other words, I want to match everything that is not a mongodb object id.

I suppose it should be as easy as negate (?!) the regex, but I am not capable of making it right.

The regex should work in Javascript and Python3 (it could be two different regexs). I can accept a small loss of precision, if needed, and the string can have space but not newlines.

For example, a full name (James Bond) should match positive, but not (45cbc4a0e4123f6920000002)

More about Mongodb object Ids.

Thanks :-)

Community
  • 1
  • 1
bustawin
  • 684
  • 7
  • 11

2 Answers2

0

This might be it:

const isNotMongoObject = id => !/^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i.test(id)

const testIds = [" James Bond ", "45cbc4a0e4123f6920000002", "112345679065574883030833", "FFFFFFFFFFFFFFFFFFFFFFFF", "45cbc4a0e4123f6920000002", ` James 
Bond `]
for (const id of testIds) {
  console.log(`${id} ${isNotMongoObject(id)}`)  
}
def isNotMongoObject id:
    return re.match(r"^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)", id) is not None
Maciej Kozieja
  • 1,812
  • 1
  • 13
  • 32
0

In regex language, the opposite would be:

^(?!(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)).+

Which yields the following results:

112345679065574883030833 => true
FFFFFFFFFFFFFFFFFFFFFFFF => true
45cbc4a0e4123f6920000002 => false (ie a mongo id)
112345679065574883030833 => true
James Bond => true

See a demo on regex101.com.
Another (better?) way would be to prove if it is a Mongo ID and then check the negation programmatically.

Jan
  • 42,290
  • 8
  • 54
  • 79