Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to validate hex string

Tags:

.net

regex

I'm using this simple regular expression to validate a hex string:

^[A-Fa-f0-9]{16}$

As you can see, I'm using a quantifier to validate that the string is 16 characters long. I was wondering if I can use another quantifier in the same regex to validate the string length to be either 16 or 18 (not 17).

like image 773
Alonso Avatar asked Nov 13 '08 17:11

Alonso


3 Answers

I believe

^([A-Fa-f0-9]{2}){8,9}$

will work.

This is nice because it generalizes to any even-length string.

like image 160
David Norman Avatar answered Nov 18 '22 18:11

David Norman


That's just a 16 character requirement with an optional 2 character afterwards:

^[A-Fa-f0-9]{16}([A-Fa-f0-9]{2})?$

The parentheses may not be required - I'm not enough of a regex guru to know offhand, I'm afraid. If anyone wants to edit it, do feel free...

like image 9
Jon Skeet Avatar answered Nov 18 '22 17:11

Jon Skeet


^(?:[A-Fa-f0-9]{16}|[A-Fa-f0-9]{18})$
like image 5
VonC Avatar answered Nov 18 '22 17:11

VonC