参考这个问题,我有一个场景,我只需要匹配包含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的正则表达式
发布评论