Alex Rivera | Logout

Regular expression to validate hex string

Asked 2008-11-13T17:51:57.773
14

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

Edit
Report

2 Answers

52

I believe

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

will work.

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

answered 2008-11-13T17:54:42.620
5
^(?:[A-Fa-f0-9]{16}|[A-Fa-f0-9]{18})$
answered 2008-11-13T17:53:24.773

Your Answer