use std::fs; use std::io; extern crate regex; // Add regex crate to your Cargo.toml use regex::Regex; fn main() -> io::Result<()> { let pattern = r"^mul\(\d{1,3},\d{1,3}\)$"; let file_contents: String = fs::read_to_string("medium.txt")?; let length_of_string = file_contents.len(); let re = Regex::new(pattern).unwrap(); let mut total: u32 = 0; let mut total2: u32 = 0; let mut enabled: bool = true; for i in 0..length_of_string { let substring = &file_contents[i..i+1]; if substring == "d" { //println!("{},{}",&file_contents[i..i+3],&file_contents[i..i+6]); if &file_contents[i..i+4] == "do()" { enabled = true; } else if &file_contents[i..i+7] == "don't()" { enabled = false; } } else if substring == "m" { let mut closed_bracket_position = 0; for j in i+3..length_of_string { let next_closed_bracket = &file_contents[j..j+1]; if next_closed_bracket == ")" { closed_bracket_position = j; break; } // check it's reached the end of string } let string_to_check = &file_contents[i..closed_bracket_position+1]; //println!("String to check is {}",&file_contents[i..closed_bracket_position+1]); if re.is_match(string_to_check) { //println!("{} is VALID!!!", string_to_check); let mut comma_position = 5; for j in 5..string_to_check.len() { if &string_to_check[j..j+1] == "," { comma_position = j; } } let number1: &Result = &string_to_check[4..comma_position].parse(); let number2: &Result = &string_to_check[comma_position+1..string_to_check.len()-1].parse(); match (number1, number2) { (Ok(n1), Ok(n2)) => { let result = n1 * n2; //println!("Multiplication result: {}", result); total = total + result; if enabled == true { total2 = total2 + result; } }, _ => { //println!("One or both of the values are invalid."); } } } } } println!("Part 1 total is: {}", total); println!("Part 2 total is: {}", total2); Ok(()) }