macross1
macross1

Reputation: 9

Regex in Rust program

I've started to learn Rust recently and I'm having some issues regarding regex. So i wanted my program to read contents of the file and check if it matches the regex.

file:

a = point ( 1 , 1 ) ;
b = point ( 2 , 2 ) ;
c = point ( 3 , 3 ) .

main.rs:

use std::env;
use std::fs::File;
use std::io::prelude::*;
extern crate regex;
use regex::Regex;

fn main() -> std::io::Result<()>{
    let args: Vec<String> = env::args().collect();

    let reg : Regex = Regex::new(r"(?s)^[a-zA-z]+[[:space:]]*=[[:space:]]*point[[:space:]]*\([[:space:]]*[0-9]+[[:space:]]*,[[:space:]]*[0-9]+[[:space:]]*\)[[:space:]]*;\n[a-zA-z]+[[:space:]]*=[[:space:]]*point[[:space:]]*\([[:space:]]*[0-9]+[[:space:]]*,[[:space:]]*[0-9]+[[:space:]]*\)[[:space:]]*;\n[a-zA-z]+[[:space:]]*=[[:space:]]*point[[:space:]]*\([[:space:]]*[0-9]+[[:space:]]*,[[:space:]]*[0-9]+[[:space:]]*\)[[:space:]]*\.$").unwrap();
    

    let text = "a = point ( 1 , 1 ) ;
b = point ( 2 , 2 ) ;
c = point ( 3 , 3 ) .";
    
    
    
    let mut file = File::open(&args[1])?;   //specify filename in argument
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
        
        
    let contents_result = reg.is_match(&contents);
    let text_result = reg.is_match(text);
    
    if contents_result == true{
        println!("success");
    }
    else{
        println!("fail");
    }
    if text_result == true{
        println!("success");
    }
    else{
        println!("fail");
    }
    
    Ok(())
}

so the string inside text is identical to the the file, But in the result matching, the text succeeded while the file fails. Any idea what am i missing here?

Upvotes: 0

Views: 1706

Answers (1)

user14398463
user14398463

Reputation:

Consider adding a couple lines to test your assumption that the file contents and text are indeed equivalent. For example, just after reading the file into contents, try adding the following lines.

println!("text = {:?}", text);
println!("contents = {:?}", contents);

This should print of each value and may help you figure out what is happening. My hunch is that the problem you're encountering may be exactly Alex Larionov pointed out, which is that the file has not been saved.

Good luck!

Upvotes: 2

Related Questions