2

I want to limit the length of hex number to 4 OR 8. For example:

0x0001 is valid (4 hex numbers)

0x0001001F is valid (8 hex numbers)

0x00012 is invalid (5 hex numbers)

I can validate a hex number with length of n (n is 4 or 8) by using

Regex.IsMatch("0x0001", "^0x[0-9a-fA-F][{n}$");

How to achieve this OR operation, say either 4 or 8, not from 4 to 8?

musefan
  • 47,875
  • 21
  • 135
  • 185
esun203
  • 167
  • 5
  • 11

1 Answers1

4

"Or" is represented by | in regex. Your regex would therefore look like

0x([0-9a-fA-F]{4}|[0-9a-fA-F]{8})

Another way would be to make the last four digits optional using ?. This would lead to

0x[0-9a-fA-F]{4}([0-9a-fA-F]{4})?
Jens
  • 25,229
  • 9
  • 75
  • 117
  • 1
    You could make it shorter by matching the group of four digits 1-2 times: `0x([0-9a-fA-F]{4}){1,2}` – Herohtar Aug 07 '19 at 19:47