Search code examples
rust

How can I check if a String is an hexadecimal value in Rust


If I have a string as input, like 0xc0ffee.

How can I check if this String represent an hexadecimal value ?


Solution

  • Generally, the correct way to do this would be to rely on the parsing functions, rather than trying to reimplement a subset of them on your own, largely because when you want to know if it's parseable as hex, it's because you actually want the parsed value in short order anyway:

    // Remove the `0x` prefix if it has one
    let trimmed = if thestring.starts_with("0x") { &thestring[2..] } else { &thestring[..] };
    
    // Ask the parser to parse in base 16 and collect the parsed value if so
    if let Ok(uval) = u64::from_str_radix(trimmed, 16) {
        // It's a valid u64, and uval is the parsed value
    } else {
        // It wasn't a valid u64
    }
    

    Substitute the appropriate integer type if u64 isn't the goal.