Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  5] [ 1]  / answers: 1 / hits: 49488  / 11 Years ago, wed, january 8, 2014, 12:00:00

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.


More From » regex

 Answers
63

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


[#73317] Monday, January 6, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
grayson questions
;