Pattern library / Strings & Text
Regex to Match Hexadecimal Strings
Matches hex digits with an optional 0x prefix. Useful for color codes, hashes, and binary data in GA4 event parameters.
How the pattern works
(0[xX])?— optional 0x or 0X prefix.[0-9a-fA-F]+— one or more hex digits.- Add
{8}or{32}to enforce a fixed length (e.g. MD5/SHA-256).
Test it: match & no-match examples
Every row is loaded straight into the tester — click Try to see the match live:
| Input | Result | Why | |
|---|---|---|---|
deadbeef | Match | lowercase hex | Try → |
0xDEADBEEF | Match | 0x prefix | Try → |
0x123 | Match | short hex | Try → |
g123 | No match | g not hex | Try → |
0x | No match | no digits after prefix | Try → |
12 34 | No match | space breaks match | Try → |
Where to use it
JavaScript
const re = /^(0[xX])?[0-9a-fA-F]+$/;
re.test('0xDEADBEEF'); // true
Python
import re re.match(r'^(0[xX])?[0-9a-fA-F]+$', 'deadbeef')
Common mistakes
Test this pattern on your own data
Paste it into the free tester with your real strings — nothing leaves your browser.
FAQ
Related patterns
For GA4-specific patterns, see the GA4 regex cheat sheet, the page path regex guide, the event filter regex guide, the GA4 regex match types, the custom channel grouping guide and RE2 vs PCRE. Browse the full regex pattern library.