Regex to Match Hexadecimal Numbers

Match hexadecimal numbers with optional 0x prefix using this regex. Validates hex strings for programming and color codes. Free tool.

Regular Expression

/^(?:0x)?[0-9a-fA-F]+$/i

Token Breakdown

TokenDescription
^Anchors at the start of the string (or line in multiline mode)
(?:Start of non-capturing group
0Matches the literal character '0'
xMatches the literal character 'x'
)End of group
?Makes the preceding element optional (zero or one times)
[0-9a-fA-F]Character class — matches any one of: 0-9a-fA-F
+Matches the preceding element one or more times (greedy)
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex matches hexadecimal numbers with an optional 0x prefix. Here is the token-by-token breakdown:

^ — Anchors the match at the start of the string, ensuring the entire input is validated as a hex number.

(?:0x)? — A non-capturing group matching the optional '0x' prefix commonly used in programming languages like C, Java, and JavaScript to denote hexadecimal literals. The ? quantifier makes the entire prefix optional, so both '0xFF' and 'FF' would match.

[0-9a-fA-F]+ — A character class matching one or more hexadecimal digits. It includes digits 0-9 and letters a-f in both lowercase and uppercase. The + quantifier requires at least one hex digit.

$ — Anchors the match at the end of the string.

The i flag makes the pattern case-insensitive, which is redundant here since the character class already includes both cases, but it provides an extra layer of clarity. Hexadecimal numbers are fundamental in computing and are used for memory addresses, color codes (like #FF5733), byte values, Unicode code points, and MAC addresses. This pattern is intentionally simple and does not validate the length of the hex string. If you need to match specific lengths (such as exactly 6 digits for color codes), you would modify the quantifier to {6} instead of +. For color codes specifically, see the hex-color-code pattern.

Example Test Strings

InputExpected
0xFFMatch
1a2b3cMatch
0xGHIJNo Match
DEADBEEFMatch
0xNo Match

Try It — Interactive Tester

//i
gimsuy
No matches found.
Pattern: 21 charsFlags: iMatches: 0

Ctrl+Shift+C to copy regex

Customize this pattern →