Alonso
Alonso

Reputation: 1109

Regular expression to validate hex string

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

Answers (4)

John Fiala
John Fiala

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

David Norman
David Norman

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

Jon Skeet
Jon Skeet

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

VonC
VonC

Reputation: 1324148

^(?:[A-Fa-f0-9]{16}|[A-Fa-f0-9]{18})$

Upvotes: 5

Related Questions