Regex to match a valid hex string but not all '0'

Viewed 165

I am trying to write a Regex to match a valid Hex string but without all zero values.

How to write a Regex to match valid hex string is a common knowledge.

The simplest is ^0[xX][0-9a-fA-F]+$.

But, among all the possible hex strings, the ones match Zero should be invalid.

e.g.,

0x0, 0x00, 0x00000 are all invalid

but

0x01, 0x001, 0x010 are valid

1 Answers

You may use a lookahead to restrict the match:

^0[xX](?!0+$)[0-9a-fA-F]+$
      ^^^^^^^

Here, after matching 0x or 0X, the (?!0+) negative lookahead fails the match if there are 1+ zeros to the end of the string immediately to the right.

See the regex demo

C# possible usage example:

if (Regex.IsMatch(s, @"^0x(?!0+$)[0-9a-f]+$", RegexOptions.IgnoreCase))
{
    // Valid
}
Related