Tuesday, March 1, 2011

Regular Expression to validate hex string

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 :)

From stackoverflow
  • ^(?:[A-Fa-f0-9]{16}|[A-Fa-f0-9]{18})$
    
  • 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...

    Tomalak : From a performance point of view, this is *a lot* better. Much less backtracking on a non-match. +1
    Jan Goyvaerts : Parentheses are required here. If you omit them, the ? makes the {2} lazy, which has no effect here.
  • 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.

    Johannes Schaub - litb : i agree that deserves upvotes
    Tomalak : Good thinking! +1
    VonC : I agree, better: +1 (if Alonso wants to put the 'tick' solution mark on this answer rather than mine, I would understand ;) )
    Tomalak : 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.
  • 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.

    Dave Sherohman : 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.

0 comments:

Post a Comment