Reputation: 1109
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).
Upvotes: 14
Views: 27936
Reputation: 4581
I'd probably go with
/^[a-f0-9]{16}([a-f0-9]{2})?$/i
myself. I think it's more readable to set the regex as case insensitive and only list the character range once. That said, just about all of these answers work.
Upvotes: 0
Reputation: 19879
I believe
^([A-Fa-f0-9]{2}){8,9}$
will work.
This is nice because it generalizes to any even-length string.
Upvotes: 52
Reputation: 1500485
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...
Upvotes: 9