tags:

views:

2165

answers:

4

Hi, 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 chars 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).

Thanks in advance :)

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

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

Jon Skeet
From a performance point of view, this is *a lot* better. Much less backtracking on a non-match. +1
Tomalak
Parentheses are required here. If you omit them, the ? makes the {2} lazy, which has no effect here.
Jan Goyvaerts
+16  A: 

I believe

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

will work.

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

EDIT: Small update based on a good comment.

David Norman
i agree that deserves upvotes
Johannes Schaub - litb
Good thinking! +1
Tomalak
I agree, better: +1 (if Alonso wants to put the 'tick' solution mark on this answer rather than mine, I would understand ;) )
VonC
The inner expression could be optimized to ([A-Fa-f0-9]{2}), maybe even to ([[:xdigit:]]{2}) or (\p{XDigit}{2}). Depending on your regex flavor, pre-constructed character classes like the POSIX one perform better than hand-made ones.
Tomalak
A: 

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 bout all of these answers work.

John Fiala
Like so many things, it's a tradeoff... /[a-f]/i may be more readable (or may not, depending on the reader), but /[A-Fa-f]/ will run faster. Probably not enough of a performance difference to be relevant in this case, though.
Dave Sherohman