match by regex instead of splitting

This commit is contained in:
Baipyrus 2024-01-25 17:38:56 +01:00
parent b38cb21b02
commit 61c576afd4
2 changed files with 10 additions and 10 deletions

View File

@ -8,23 +8,23 @@ pub fn split_lines(input: &str) -> Vec<String> {
.collect() .collect()
} }
pub fn split_input(entry: &str, re: &str) -> Vec<String> { pub fn match_input(entry: &str, re: &str) -> Vec<String> {
let regex = Regex::new(re) let regex = Regex::new(re)
.expect("Invalid regex"); .expect("Invalid regex provided!");
let split: Vec<String> = regex let matches: Vec<String> = regex
.split(entry) .find_iter(entry)
.map(|s| s.to_string()) .map(|m| m.as_str().to_string())
.collect(); .collect();
split matches
} }
pub fn split_inputs(input: Vec<String>, re: &str) -> Vec<Vec<String>> { pub fn match_inputs(input: Vec<String>, re: &str) -> Vec<Vec<String>> {
let mut result = Vec::new(); let mut result = Vec::new();
for entry in input { for entry in input {
let split = split_input(&entry, re); let split = match_input(&entry, re);
result.push(split); result.push(split);
} }

View File

@ -1,4 +1,4 @@
use crate::common::{convert_num, read_file, split_inputs, split_lines}; use crate::common::{convert_num, read_file, match_inputs, split_lines};
#[allow(dead_code)] #[allow(dead_code)]
pub fn part_two() { pub fn part_two() {
@ -122,6 +122,6 @@ fn setup() -> Vec<Vec<i32>> {
let content = read_file(name); let content = read_file(name);
let lines = split_lines(&content); let lines = split_lines(&content);
let input = split_inputs(lines, &r"\s+"); let input = match_inputs(lines, &r"\s*-?\d+\s*");
convert_num(input) convert_num(input)
} }