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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With