RustでDIMACS CNF ファイルを読み込みたいです。
Rubyで書くと以下のようなコードになるのですがRustだとどう書けばいいでしょうか?
特に、Rubyのscanに当たる関数が見つかってないです。
#Ruby code
def read_dimacs_cnf_file(file_name)
cnf=[]
clause=[]
open(file_name,"r").readlines.reject{|line| line=~/^c/ || line=~/^p/}.join().scan(/-?\d+/).collect{|literal| literal.to_i}.each{|literal|
if literal==0
then
cnf<<clause
clause=[]
else
clause<<literal
end
}
cnf
end
入力例
c
c comment
c
p cnf 3 3
1 2 0
2 -3 0
3 0
出力例
[[1,2],[2,-3],[3]]
RustのコードはFileを読み込むところまでしか書けてないです。
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn read_dimacs_cnf_file(file_name:&str)->String{
let path=Path::new(file_name);
let mut file=match File::open(&path){
Err(msg) => panic!("couldn't open file. {}",msg),
Ok(file) => file,
};
let mut s=String::new();
match file.read_to_string(&mut s){
Err(msg) => panic!("couldn't read file. {}",msg),
Ok(_) => return s,
};
}
fn main() {
println!("{}",read_dimacs_cnf_file("test.cnf"));
}