use regex::Regex; use std::io::{self, Read, Write}; fn main() -> Result<(), Box> { let mut raw = Vec::new(); let mut stdin = io::stdin().lock(); stdin.read_to_end(&mut raw)?; let text = String::from_utf8_lossy(&raw).into_owned(); // 1. // de-hyphen let dehyphenate_re = Regex::new(r"-\s+\n").unwrap(); let text = dehyphenate_re.replace_all(&text, ""); // 2. de-paragraph let deparagraph_re = Regex::new(r"(\S)[ \t]+\n(\w)").unwrap(); let text = deparagraph_re.replace_all(&text, "$1 $2"); // 2. Remove lines with just numbers (often page numbers) let depagenumber_re = Regex::new(r"\n\d+\n").unwrap(); let text = depagenumber_re.replace_all(&text, "\n\n"); // 2. Remove any lines with just 1 to 3 characters let shorttext_re = Regex::new(r"(?m)^.{1,3}\s*?$").unwrap(); let text = shorttext_re.replace_all(&text, "\n"); // 2. Remove longer "weird" lines with lots of punctuation and few characters let shorttext_re = Regex::new(r"(?m)^.{0,6}[[:punct:]]{1,5}.{0,6} *$").unwrap(); let text = shorttext_re.replace_all(&text, ""); // normalise all multi-newlines to be just double let many_newlines_re = Regex::new(r"\n{3,}").unwrap(); let text = many_newlines_re.replace_all(&text, "\n\n"); let mut stdout = io::stdout().lock(); stdout.write_all(text.as_bytes())?; stdout.flush()?; Ok(()) } fn _unwrap_paragraph(paragraph: &str, _title_min_alpha: usize) -> String { if paragraph.trim().is_empty() { return paragraph.to_owned(); } // Split into lines but keep content; we will optionally preserve the first line if it's a title. let mut lines = paragraph.lines(); let first = lines.next().unwrap_or_default(); let rest = lines.collect::>().join("\n"); // TODO this doesn't figure ot Mr.\nBlake, or M.J.\nWeissman let re_dehyphen = Regex::new(r"(?m)\n([a-z])").unwrap(); // let re_newlines = Regex::new(r"\n+").unwrap(); // Process the "rest" chunk: dehyphenate, then collapse newlines to spaces. let rest_processed = re_dehyphen.replace_all(&rest, " $1").into_owned(); if rest_processed.is_empty() { first.to_owned() } else { // No title: join first line with the rest using a space/newline rule. // Handle dehyphenation across the boundary too. // If first ends with '-' and rest starts with lowercase, drop the hyphen and space. let starts_lower = rest_processed .chars() .next() .map(|c| c.is_ascii_lowercase()) .unwrap_or(false); if first.ends_with('-') && starts_lower { format!("{}{}", &first[..first.len() - 1], rest_processed) } else { format!("{} {}", first, rest_processed) } } }