Skip to content

Regex for Hex — Pattern, Examples & Caveats

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

This pattern matches a hexadecimal number, optionally prefixed with 0x or 0X, consisting of one or more hex digits. It is useful for validating memory addresses, color components, hashes and other base-16 values. Numeric patterns validate or extract numbers in a particular notation — integers, decimals, scientific notation, hex, binary or currency. The hard part is bounding ranges and forbidding malformed forms (leading zeros, stray signs, misplaced separators) that a naive \d+ would accept. Always pair a numeric regex with a real parse when magnitude, overflow or precision matter. It needs no special flags. Apply it to the whole input as a format contract. It accepts both cases and an optional prefix; normalize before comparing values. It does not bound the length, so arbitrarily long hex strings pass — add {n} if you expect a fixed width like a 64-char SHA-256. A leading 0x is optional, so 0x1A and 1A both match; decide which form your system canonicalizes to. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • (0[xX])? — optional 0x or 0X prefix
  • [0-9a-fA-F]+ — one or more hexadecimal digits
  • ^...$ — anchors ensuring the entire string is hex

What it matches

1a2b3c0xFFDEADBEEF0x0ff00aa

What it does not match

0xGG123g0xhex12 34

When to use it

Reach for a numeric pattern when input must be a number in a specific notation, such as a quantity, a price, a coordinate or a bit string. Validate the textual shape first, then parse to a numeric type and check range, precision and overflow in code, because regex cannot reliably bound magnitude. Decide explicitly whether signs, leading zeros, separators and exponents are allowed, and document that contract so producers and consumers of the data agree on the accepted form.

Caveats

  • It accepts both cases and an optional prefix; normalize before comparing values.
  • It does not bound the length, so arbitrarily long hex strings pass — add {n} if you expect a fixed width like a 64-char SHA-256.
  • A leading 0x is optional, so 0x1A and 1A both match; decide which form your system canonicalizes to.

Code examples

JavaScript
const re = /^(0[xX])?[0-9a-fA-F]+$/;
const input = "1a2b3c";
if (re.test(input)) {
  // valid: proceed
} else {
  // reject with a helpful message
}
Python
import re

rx = re.compile(r"^(0[xX])?[0-9a-fA-F]+$")
value = "1a2b3c"
if rx.fullmatch(value):
    pass  # valid
else:
    raise ValueError("invalid format")
Java
import java.util.regex.*;

Pattern p = Pattern.compile("^(0[xX])?[0-9a-fA-F]+$");
Matcher m = p.matcher("1a2b3c");
boolean ok = m.matches();   // whole input must conform
PHP
<?php
$subject = "1a2b3c";
if (preg_match('/^(0[xX])?[0-9a-fA-F]+$/', $subject, $m)) {
    // $m[0] is the full match
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

How do I match a SHA-256 hash exactly?

Use ^[0-9a-fA-F]{64}$ for a 64-digit hex SHA-256, or {40} for SHA-1 and {32} for MD5. Fixed-width bounds prevent partial matches.

Does it accept uppercase hex?

Yes — the class includes A-F as well as a-f, so both cases match. Lowercase the result if you need a canonical form.

Can a regex fully validate a number's range?

Only awkwardly. Digit classes accept out-of-range values (e.g. \d{1,3} allows 999), so precise bounds need alternation like 25[0-5]|2[0-4]\d. For most cases, match the shape then parse and range-check in code.

Why are leading zeros often rejected?

Leading zeros are ambiguous: 010 may mean decimal 10 or octal 8, and canonical numbers do not use them. Patterns like (0|[1-9]\d*) forbid them so the textual form maps unambiguously to a value.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →