Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching hexadecimal numbers?

Tags:

c#

regex

hex

match

So I'm trying to figure out how to use regex to to match a hex string. The current regex I'm using is:

[^0]+

I want it to match: 50 6C 65 63 74 72 6F 6E 73 given:

50 6C 65 63 74 72 6F 6E 73 00 00 00 00 00 00 00 
64 35 75 73 70 73 34 00 01 00 00 00 00 00 00 00 
52 61 79 74 69 6E 00 00 00 00 00 00 00 00 00 00 
63 38 63 61 70 73 34 00 01 00 00 00 00 00 00 00 
92 B6 B3 F5 00 00 00 01 8A 68 58 DD 00 00 00 00 
00 00 00 00 

but it only matches 50.

When using this hex string it works the way I want it to:

52 61 79 74 69 6E 00 00 00 00 00 00 00 00 00 00 
63 38 63 61 70 73 34 00 01 00 00 00 00 00 00 00 
52 69 70 74 69 64 65 31 30 33 30 00 00 00 00 00 
64 32 75 73 70 73 34 00 01 00 00 00 00 00 00 00 
B3 F4 0A 88 00 00 00 1F C0 95 41 99 00 00 00 00 
00 00 00 00 

matches 52 61 79 74 69 6E

like image 810
Adam Osborne Avatar asked Aug 30 '25 18:08

Adam Osborne


2 Answers

This will match number by number:

[a-fA-F0-9]{2}

Online example

This will match the whole string:

^([a-fA-F0-9]{2}\s+)+

Online example

like image 196
aybe Avatar answered Sep 02 '25 08:09

aybe


I'm a little confused at how your regex is matching 50 and not just 5. But in general, the problem with your regex is that it is just going until it hits a 0, and what you want is for it to go until you hit two consecutive zeros. The standard way to do this is with a look-around:

.+?(?= 00)

The .+ will match any characters for as long as possible. The second part of the regular expression (called a positive lookahead) searches for two zeros and terminates the match just before the occurrence of the 00. The reason for doing .+? instead of just .+ is that the latter will match everything until the last 00, whereas you only want everything up until the first 00. The ? converts the .+ into a lazy regex, so it matches the minimum required rather than the maximum possible. In this case it means that it'll match until the first 00 instead of the last 00.

Note that inside the look-around I included a space so that your match would not include a space at the end of the string. Not sure if that matters to you.

like image 39
Vyas Avatar answered Sep 02 '25 08:09

Vyas