Jake
Jake

Reputation: 26117

Regex to match 8 or 12 or 32 hex number

I am trying to write a regex for a case-insensitive hex number that should match either 8 or 12 or 32 in length.

The regex I have so far is:

/^[0-9A-F]{8}|[0-9A-F]{12}|[0-9A-F]{32}$/i

The pattern I am trying to test against is:
96AFC4ADA8C44A36B0CB1EC28531C3BC

or

870b72a9a020

or

569ac61e

But this doesn't seem to be matching the criteria.

Can you help?

Thanks,

Upvotes: 1

Views: 4830

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149020

You could use something like this:

/^[0-9A-F]{8}([0-9A-F]{4}([0-9A-F]{20})?)?$/i

This will match 32 digits if the inner-most group is present, 12 digits if the middle group is present but not the inner-most group, and 8 digits if neither of the inner groups are present.

Upvotes: 4

Barmar
Barmar

Reputation: 780974

Your approach was basically right, but you need to take ^ and $ out of the alternatives, so they apply to the regexp as a whole:

/^(?:[0-9A-F]{8}|[0-9A-F]{12}|[0-9A-F]{32})$/i

Upvotes: 5

Related Questions