MongoDB ObjectID的正则表达式 [英] Regex for MongoDB ObjectID

查看:906
本文介绍了MongoDB ObjectID的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考这个问题,我有一个场景,我只需要匹配包含af的十六进制字符串。其他一切都不匹配。示例:

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

我的用例是我正在使用一组十六进制字符串并且只想验证同样是那些mongodb objectIDs。

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.

推荐答案

您可以使用以下正则表达式但它不会完全正常工作

You can use following regular expression but it will not quite work

checkForHexRegExp = /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i

示例:

> checkForHexRegExp.test("112345679065574883030833")
false
> checkForHexRegExp.test("FFFFFFFFFFFFFFFFFFFFFFFF")
false
> checkForHexRegExp.test("45cbc4a0e4123f6920000002")
true

但是,正如我评论的那样, 112345679065574883030833 FFFFFFFFFFFFFFFFFFFFFFFF 也是有效的十六进制表示。

But, as I commented, 112345679065574883030833, FFFFFFFFFFFFFFFFFFFFFFFF are also valid hexadecimal representations.

你应该使用 / ^ [af\d] {24} $ / i 因为它通过了所有上述测试

You should use /^[a-f\d]{24}$/i because it passes all the above tests

这篇关于MongoDB ObjectID的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆