abdoe
abdoe

Reputation: 459

How do I a match string with further processing?

I'm reading some file, line by line and want to match each line, to verify if it contains a specific string.

What I have so far:

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

This results in:

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

Can I use match to check for different containing strings, like I'd do with switch in other cases?

As in, something like:

fn parse_line(line: String) {
    match line {
        line.contains("foo") => print!("function foo"),
        line.contains("bar") => print!("function bar"),
        _ => print!("function body"),
    }
}

Upvotes: 2

Views: 847

Answers (1)

Boiethios
Boiethios

Reputation: 42869

Use an if in your match, called a 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"),
    }
}

Note that this line:

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

is not Rust. There is no syntax like that in Rust.

Upvotes: 4

Related Questions