Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

checkForHexRegExp = /^(?=[a-fd]{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-fd]{24}$/i because it passes all the above tests


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...