regexrust

Extract values from string using regex


I am using this regex to extract 3 values from a string:

'Rgba\(\n.*\n.*?(?<digits0>\d{1,3},)\n.*?(?<digits1>\d{1,3},)\n.*?(?<digits2>\d{1,3},)\n.*\n.*\n.*

I'm using this to capture the first 3 values and comma for first 2 values from the following output:

'Rgba(
    [
        89,
        89,
        89,
        255,
    ],
)'

I am not sure how to do this properly with split() or some other method to extract the 3 values (I don't care if it's all 4 values for that matter).

I am doing a capture and then a format! to join them, so I can test it contains the 3 values.

Can someone help me simplify this at all?

My current attempt is:

With the input string of:

'Rgba(
    [
        89,
        89,
        89,
        255,
    ],
)'
let mut reg_test = Regex::new(r"'Rgba\(\n.*\n.*?(?<digits0>\d{1,3},)\n.*?(?<digits1>\d{1,3},)\n.*?(?<digits2>\d{1,3}),\n.*\n.*\n.*").unwrap();
let Some(caps) = reg_test.captures(&text_string) else {
                            println!("no match!");
                            return;
                        };
let joined_text = format!("{}{}{}", &caps["digits0"], &caps["digits1"], &caps["digits2"]).contains("0,0,0");
println!("Result: {}", joined_text);

Output is 89,89,89


Solution

  • fn extract_values(input: &str) -> Vec<u32> {
        input
            .lines()
            .filter_map(|line| {
                line.trim()
                    .trim_end_matches(',')
                    .parse::<u32>()
                    .ok()
            })
            .collect()
    }
    
    fn main() {
        let input = r#"
            Rgba(
                [
                    89,
                    89,
                    89,
                    255,
                ],
            )
        "#;
    
        let values = extract_values(input);
        
        if values.len() >= 3 {
            let joined_text = format!("{},{},{}", values[0], values[1], values[2]);
            let contains_zeros = joined_text.contains("0,0,0");
            println!("Extracted values: {:?}", values);
            println!("Does it contain 0,0,0? {}", contains_zeros);
        } else {
            println!("Not enough values found");
        }
    }