gpt4 book ai didi

rust - 在 for 循环中使用正则表达式

转载 作者:行者123 更新时间:2023-12-03 11:27:32 24 4
gpt4 key购买 nike

我正在学习 Rust 并尝试在 for 循环读取一行中应用正则表达式。

extern crate regex;
use regex::Regex;

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

fn main() -> Result<()> {
let file = File::open("logs.log")?;
let reader = BufReader::new(file);

let re = Regex::new(r"^\w{3}\s{1,2}\d{1,2}\s(?:\d{2}:){2}\d{2}").unwrap();

for line in reader.lines() {
println!("{}", re.is_match(line));
}

Ok(())
}

使用 cargo run 我收到上面的错误

  --> src/main.rs:14:36
|
14 | println!("{}", re.is_match(line));
| ^^^^ expected `&str`, found enum `std::result::Result`
|
= note: expected reference `&str`
found enum `std::result::Result<String, std::io::Error>`

使用 rustc file.rs,接收这个

| extern crate regex;
| ^^^^^^^^^^^^^^^^^^^ can't find crate

这是应用正则表达式的正确方法吗?

最佳答案

From the docs on BufRead::lines :

The iterator returned from this function will yield instances of io::Result<String>. Each string returned will not have a newline byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.

(强调我的)

你的 line变量是 Result<String> ,但您尝试调用 re.is_match在它上面就像一根绳子。由于您的 main函数已经返回 Result ,最干净的解决方案是使用 ? operator (发音为“try operator”)返回 Err无论何时line是一个 Err :

for line in reader.lines() {
println!("{}", re.is_match(&line?));
}

您还需要 &line而不是 line , 因为函数需要 &str , 不是 String .

关于rust - 在 for 循环中使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65572067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com