如何进一步处理匹配字符串?
问题描述:
我正在逐行阅读一些文件,并希望匹配每一行,以验证它是否包含特定的字符串。如何进一步处理匹配字符串?
我到目前为止有:
// read file line by line
let file = File::open(file_path).expect("Cannot open file");
let buffer = BufReader::new(file);
for line in buffer.lines() {
// println!("{:?}", line.unwrap());
parse_line(line.unwrap());
}
fn parse_line(line: String) {
match line {
(String) if line.contains("foo") => print!("function head"),
_ => print!("function body"),
}
}
这导致:
error: expected one of `,` or `@`, found `)`
--> src/main.rs:13:20
|
13 | (String) if line.contains("foo") => print!("function head"),
| ^expected one of `,` or `@` here
我可以使用match
检查不同的包含字符串,就像我在其他情况下switch
呢?
,是这样的:
fn parse_line(line: String) {
match line {
line.contains("foo") => print!("function foo"),
line.contains("bar") => print!("function bar"),
_ => print!("function body"),
}
}
答
在match
使用的if
,称为match guard:
fn main() {
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
let file_path = "foo.txt";
// read file line by line
let file = File::open(file_path).expect("Cannot open file");
let buffer = BufReader::new(file);
for line in buffer.lines() {
parse_line(line.unwrap());
}
}
fn parse_line(line: String) {
match line {
ref s if s.contains("foo") => print!("contains foo"),
ref s if s.contains("bar") => print!("contains bar"),
_ => print!("other"),
}
}
需要注意的是这一行:
(String) if line.contains("foo") => print!("function head");
是不生锈。在Rust中没有这样的语法。