Start learning free

LESSON 15 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -v in Rust: Inverting a Match with !contains()

Practice Read the full explanation

Build the -v flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that DO NOT contain pattern as a substring (case-sensitive). Return the remaining lines (the ones that do not contain the pattern), in their original order, joined by newline characters (\n).

Function signature:

fn grep_invert(lines: Vec<String>, pattern: String) -> String

Example:

Input:
pattern = "err"
lines = ["error", "ok", "another error", "fine"]

Output: "ok\nfine"

When printed:
ok
fine

If every line contains the pattern, return the empty string "".


Same as grep v1 but flip the condition: keep the lines where !line.contains(pattern.as_str()) is true, then return result.join("\n").

The full solution:
impl Solution {
    fn grep_invert(lines: Vec<String>, pattern: String) -> String {
        let mut result: Vec<String> = Vec::new();
        for line in &lines {
            if !line.contains(pattern.as_str()) {
                result.push(line.clone());
            }
        }
        return result.join("\n");
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Grep V3 in Rust, explained

    Problem overview

    This version builds the -v flag of grep, which inverts the match. The function grep_invert takes a Vec<String> of lines and a pattern, and returns every line that does not contain the pattern. The check is case-sensitive, the lines stay in their original order, and they are joined with \n. When every line contains the pattern, the result is the empty string.

    For pattern = "err" and lines = ["error", "ok", "another error", "fine"], the lines with err are dropped and the result is "ok\nfine".

    Approach: the same filter with the test flipped

    The first grep version kept a line when contains was true. This version keeps it when contains is false. Nothing else changes: the loop, the vector of kept lines and the final join("\n") are the same.

    In Rust, the logical negation is the prefix operator !. Writing !line.contains(...) applies it to the whole call: the method runs first, and its boolean result is flipped. There is no not keyword in Rust.

    The empty result needs no special code. If every line contains the pattern, nothing is ever pushed, the vector stays empty, and joining an empty vector gives "".

    Step by step

    1. Create the result vector as a let mut Vec<String> that will hold the lines without the pattern.
    2. Loop over the lines by reference with for line in &lines. The vector is only borrowed, so it is still there after the loop.
    3. Test for absence. Put ! in front of line.contains(pattern.as_str()). The condition is now true exactly for lines that do not contain the pattern. The lesson passes pattern.as_str(), which turns the String into a plain text slice for contains.
    4. Keep the line. Inside the if, result.push(line.clone()) adds an owned copy of the line.
    5. Join and return. result.join("\n") separates the kept lines with newlines and gives the empty string when none were kept.

    The solution in Rust

    impl Solution {
        fn grep_invert(lines: Vec<String>, pattern: String) -> String {
            let mut result: Vec<String> = Vec::new();
            for line in &lines {
                if !line.contains(pattern.as_str()) {
                    result.push(line.clone());
                }
            }
            return result.join("\n");
        }
    }
    

    Rust details worth knowing:

    • pattern.as_str() against &pattern. Both work as the argument of contains. as_str() returns a &str view of the String's contents without copying them, and the String remains usable afterwards.
    • Precedence of !. A method call binds tighter than the prefix !, so !line.contains(x) means !(line.contains(x)). No extra parentheses are needed.
    • Why clone(). line is a reference into lines. The result vector must own its strings, so each kept line is copied.
    • join and empty input. Joining a vector with one element returns that element, and joining an empty vector returns the empty string.

    Complexity

    Time: roughly O(m), where m is the total length of all lines. Each line is searched once, and the kept lines are copied and joined in linear time.

    Space: O(k), where k is the total length of the kept lines.

    Edge cases and common mistakes

    • Every line matches. For ["error", "another error"] and the pattern "err", the result is "".
    • Case still matters. With the pattern "err" on ["Error", "ok"], "Error" does not contain a lowercase err, so both lines are kept: "Error\nok".
    • Empty lines are lines. An empty line doesn't contain a non-empty pattern, so it is kept. With ["a", "", "b"] and the pattern "z", the result is "a\n\nb", which has a blank line in the middle.
    • Empty pattern. Every line contains the empty string, so nothing is kept and the result is "".
    • Empty list. The loop doesn't run, and the result is "".
    • Forgetting the !. Without it the function behaves like the previous version and returns the opposite set of lines.
    • Negating the wrong thing. Pushing the line in an else branch is an equivalent option, but flipping the condition is shorter.

    Testing

    Inputs worth trying, with the results the function returns:

    • "err" on ["error", "ok", "another error", "fine"] gives "ok\nfine".
    • "err" on ["error", "another error"] gives "".
    • "err" on ["Error", "ok"] gives "Error\nok".
    • "z" on ["a", "", "b"] gives "a\n\nb".
    • An empty pattern on ["a", "b"] gives "".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free