string - 如何进一步处理匹配字符串?

标签 string rust match

我正在逐行读取一些文件,并希望匹配每一行,以验证它是否包含特定字符串。

到目前为止我所拥有的:

// 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"),
    }
}

最佳答案

匹配中使用if,称为match guard :

use std::fs::File;
use std::io::{self, BufReader, BufRead};

fn main() -> io::Result<()> {
    let file_path = "foo.txt";
    // read file line by line
    let file = File::open(file_path)?;
    let reader = BufReader::new(file);

    for line in reader.lines() {
        parse_line(line?);
    }

    Ok(())
}

fn parse_line(line: String) {
    match &line {
        s if s.contains("foo") => print!("contains foo"),
        s if s.contains("bar") => print!("contains bar"),
        _ => print!("other"),
    }
}

请注意这一行:

(String) if line.contains("foo") => print!("function head");

不是 Rust。 Rust 中没有类似的语法。

关于string - 如何进一步处理匹配字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45916094/

相关文章:

c - 为什么我的字符串在复制时被截断了?

rust - 如何在测试中运行并发任务? [复制]

r-在向量中找到两个最接近的值

string - Lua string.match() 问题

php - 如何使用仅返回具有特定字段值的行的 MATCH AGAINST 方法搜索 MySQL 数据库?

c - 在 C 中返回指向字符串的指针时出现问题

javascript - 如何在 JavaScript 中使用运算符 "^"?

string - 戈兰 : verify that string is a valid hex string?

rust - 可变地传递一个不变地借用的变量

javascript - Wasm-bindgen:u8数组作为输入和输出,生成的javascript具有不同的函数签名