Home > Back-end >  Match a sequence of arbitrary bytes from a hex string
Match a sequence of arbitrary bytes from a hex string

Time:08-04

I am trying to craft a Regex expression to match the raw arbitrary bytes from a hex string.

I am using the regex::bytes module which allows me to enforce regex on bytes and hex to decode to hex string and I have the following code:

use hex;
use regex::bytes::Regex;

fn main() {
    let data = hex::decode("48656c6c6f20776f726c64").unwrap(); // Convert's "Hello World" 's hex string to raw bytes.
    println!("{:?}",data); // [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] , raw bytes of "Hello World"
    let data_re = Regex::new(r"").unwrap(); // What expression should go here?
    println!("{}",data_re.is_match(&data));
}

What Regex expression should go in the r"" on line 7 to match the raw bytes of the hello world hex string?

CodePudding user response:

What Regex expression should go in the r"" on line 7 to match the raw bytes of the hello world hex string?

The expression you're looking for is:

&data
    .iter()
    .map(|b| format!("\\x{:02x}", b))
    .collect::<Vec<_>>()
    .join("")

In your example, it will produce the string \x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64, but will work for arbitrary slice (or other iterable) of bytes.

  • Related