Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[macro_use] extern crate lazy_static;
- extern crate regex;
- use std::env;
- use std::fs::File;
- use std::io::BufReader;
- use std::io::prelude::*;
- use regex::Regex;
- fn environment_regex(env: &str) -> (Regex, Regex) {
- let begin_reg_string: String = "[[:space:]]*\\\\begin\\{".to_owned() + env + "\\}[[:space:]]*";
- let end_reg_string: String = "[[:space:]]*\\\\end\\{".to_owned() + env + "\\}[[:space:]]*";
- let begin_regex = Regex::new(&begin_reg_string).unwrap();
- let end_regex = Regex::new(&end_reg_string).unwrap();
- return (begin_regex, end_regex)
- }
- struct Equation {
- text: String,
- label: String
- }
- fn recognize_label(line: &str) -> Option<(&str, &str)> {
- lazy_static! {
- static ref RE: Regex = Regex::new(r"[[:space:]]*\\label\{([[:alnum:]-]*):([^\}]*)\}").unwrap();
- }
- let caps = RE.captures(line);
- if caps.is_none() {
- return None
- }
- let caps = caps.unwrap();
- if caps.get(1).is_none() || caps.get(2).is_none() {
- return None
- } else {
- return Some((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()))
- }
- }
- fn main() {
- let args: Vec<String> = env::args().collect();
- let filename = &args[1];
- let f = File::open(filename).expect("File not found.");
- let f = BufReader::new(f);
- let (begin_equation, end_equation) = environment_regex("equation");
- let (begin_align, end_align) = environment_regex("align");
- let mut equations: Vec<Equation> = Vec::new();
- let mut lines_iter = f.lines();
- 'outer: loop {
- let line = lines_iter.next();
- if line.is_none() {
- break;
- }
- // the second unwrap to get the line out of the option
- let line = line.unwrap().unwrap();
- if begin_equation.is_match(&line) {
- let mut text = String::new();
- let mut label = String::new();
- loop {
- let next_line = lines_iter.next();
- if next_line.is_none() {
- break 'outer;
- }
- let next_line = next_line.unwrap().unwrap();
- if end_equation.is_match(&next_line) {
- equations.push(
- Equation{
- text,
- label
- }
- );
- break;
- }
- let label_string = recognize_label(&next_line);
- if label_string.is_none() {
- text += &next_line;
- text.push('\n');
- } else {
- let (kind, key) = label_string.unwrap();
- label += key;
- }
- }
- }
- }
- for equation in equations {
- println!("== {} ==", equation.label);
- println!("{}", equation.text);
- }
- }
Add Comment
Please, Sign In to add comment