Start learning free

LESSON 16 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -w in Rust: Whole-Word Matching with match_indices()

Practice Read the full explanation

Build the -w flag of the Unix grep command. Given a list of lines and a search pattern (a single word made of letters, digits, and underscores), return all lines that contain pattern as a WHOLE word — i.e. the characters immediately before and after the match must NOT be word characters (letters, digits, or underscores). The match is case-sensitive.

Return the matching lines joined by newline characters (\n).

Function signature:

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

Example:

Input:
pattern = "cat"
lines = ["cat sat", "concat", "the cat", "category"]

Output: "cat sat\nthe cat"

When printed:
cat sat
the cat

Notice that "concat" is rejected because cat is preceded by the word character n (con|cat), and "category" is rejected because cat is followed by the word character e.

A line may contain the pattern more than once. It is selected if at least one occurrence is a whole word: with pattern "cat", the line "concat cat" is selected because of its second cat. The lines contain only ASCII characters.

If no lines match, return the empty string "".


The standard library has no regex engine, so find each occurrence of pattern with str::match_indices, then check that the byte to its LEFT and the byte to its RIGHT are NOT word characters (or are the line edge).

Helper for word-char detection:
fn is_word_char(c: u8) -> bool {
    (c >= b'a' && c <= b'z') || (c >= b'A' && c <= b'Z')
        || (c >= b'0' && c <= b'9') || c == b'_'
}
For each (pos, _) from line.match_indices(...), accept the line only when both edges are non-word characters.

The full solution:
impl Solution {
    fn is_word_char(c: u8) -> bool {
        (c >= b'a' && c <= b'z') || (c >= b'A' && c <= b'Z') || (c >= b'0' && c <= b'9') || c == b'_'
    }
    fn grep_word(lines: Vec<String>, pattern: String) -> String {
        let mut result: Vec<String> = Vec::new();
        let m = pattern.len();
        for line in &lines {
            let bytes = line.as_bytes();
            let n = bytes.len();
            let mut found = false;
            for (pos, _) in line.match_indices(pattern.as_str()) {
                let left_ok = pos == 0 || !Solution::is_word_char(bytes[pos - 1]);
                let right_ok = pos + m == n || !Solution::is_word_char(bytes[pos + m]);
                if left_ok && right_ok {
                    found = true;
                    break;
                }
            }
            if found {
                result.push(line.clone());
            }
        }
        result.join("\n")
    }
}

STEP 1 OF 14
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in Rust, explained

    Problem overview

    This version builds the -w flag of grep. The function grep_word takes a Vec<String> of lines and a pattern that is a single word made of letters, digits and underscores. It returns the lines that contain the pattern as a whole word, joined with \n. A match is a whole word when the character just before it and the character just after it are not word characters, where a word character is a letter, a digit or an underscore. The match is case-sensitive, and the lines are ASCII.

    With pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". "concat" is rejected because the letter n comes right before cat, and "category" is rejected because the letter e comes right after it. A line with several occurrences is kept if at least one of them is a whole word, so "concat cat" is selected because of its second cat.

    Approach: find every occurrence and check its neighbours

    A plain contains isn't enough, because it only says that the text appears somewhere. The first occurrence might be inside a longer word, with a later one standing alone. So the function must look at every occurrence of the pattern in the line, one at a time, and test the bytes on both sides of it.

    For an occurrence that starts at byte position pos and has length m, the left neighbour is at pos - 1 and the right neighbour is at pos + m. Each side can also be the edge of the line, which counts as a boundary: there is no character there, so it can't be a word character.

    • The left side is fine when pos == 0 or the byte at pos - 1 isn't a word character.
    • The right side is fine when pos + m equals the line's length, or the byte at pos + m isn't a word character.

    When both sides are fine, the line is selected and the search stops, since one whole-word occurrence is enough.

    For "concat cat", the occurrences of cat start at positions 3 and 7. At 3 the left neighbour is n, so the left check fails. At 7 the left neighbour is a space and the match ends at the end of the line, so both checks pass and the line is kept. For "category" the only occurrence starts at 0, and the right neighbour is e, so the right check fails.

    Step by step

    1. Create the result vector as a let mut Vec<String>. The starter code already provides is_word_char, which tells whether a byte is a letter, a digit or an underscore.
    2. Store the pattern's length in m. It is needed to find the byte just after a match.
    3. Loop over the lines with for line in &lines.
    4. View the line as bytes with line.as_bytes(). Bytes can be read by position, which makes it easy to look at neighbours.
    5. Store the line's length in n. It marks the right edge.
    6. Start a flag found at false. It becomes true when this line has a whole-word match.
    7. Loop over the occurrences with line.match_indices(pattern.as_str()). Each item is a pair of the position and the matched text, and the pattern (pos, _) keeps the position and ignores the text.
    8. Check the left side and store it in left_ok: pos is 0, or the byte before the match is not a word character.
    9. Check the right side and store it in right_ok: the match ends exactly at the end of the line, or the byte after it is not a word character.
    10. Require both with if left_ok && right_ok.
    11. Record the hit and stop. Set found to true and break out of the loop over occurrences. Looking further would be wasted work.
    12. After the occurrence loop, test found with an if.
    13. Keep the line. Push line.clone() onto result.
    14. Join and return with result.join("\n"), after the loop over lines. It is the empty string when nothing was kept.

    The solution in Rust

    impl Solution {
        fn is_word_char(c: u8) -> bool {
            (c >= b'a' && c <= b'z')
                || (c >= b'A' && c <= b'Z')
                || (c >= b'0' && c <= b'9')
                || c == b'_'
        }
        fn grep_word(lines: Vec<String>, pattern: String) -> String {
            let mut result: Vec<String> = Vec::new();
            let m = pattern.len();
            for line in &lines {
                let bytes = line.as_bytes();
                let n = bytes.len();
                let mut found = false;
                for (pos, _) in line.match_indices(pattern.as_str()) {
                    let left_ok = pos == 0 || !Solution::is_word_char(bytes[pos - 1]);
                    let right_ok = pos + m == n || !Solution::is_word_char(bytes[pos + m]);
                    if left_ok && right_ok {
                        found = true;
                        break;
                    }
                }
                if found {
                    result.push(line.clone());
                }
            }
            result.join("\n")
        }
    }
    

    Rust details worth knowing:

    • Short-circuit evaluation protects the indexing. In pos == 0 || ... bytes[pos - 1], the right side runs only when pos is not 0. Otherwise pos - 1 would underflow a usize, which panics in a debug build and wraps to a huge index in an optimized one, where the indexing would then panic. The same idea protects bytes[pos + m]: it is read only when pos + m differs from n, so the index is always valid.
    • Bytes, not characters. as_bytes() gives a &[u8], and match_indices reports byte positions, so the two agree. That is why is_word_char takes a u8 and compares it with byte literals such as b'a'. For ASCII text, as in this lesson, one byte is one character.
    • Solution::is_word_char. The helper takes no self, so it is called through the type name. Self::is_word_char is another way to write it.
    • The tuple pattern. match_indices yields (usize, &str). The underscore in (pos, _) discards the matched text, which would be the pattern again.
    • Non-overlapping matches. match_indices doesn't report overlapping occurrences. In "aaaa", the pattern "aa" is found at positions 0 and 2, not at 1.
    • The last expression. The function ends with result.join("\n"), without return or a semicolon, so that is the value it returns.

    Complexity

    Time: roughly O(L), where L is the total length of all lines. For each line, match_indices scans the line once, and every occurrence gets a constant-time neighbour check. The loop can stop early on a hit.

    Space: O(k), where k is the total length of the kept lines. Viewing a line as bytes copies nothing.

    Edge cases and common mistakes

    • Checking only the first occurrence. For "concat cat" the first occurrence is inside concat. A function that stopped there would wrongly reject the line. The loop must try every occurrence.
    • Underscores and digits are word characters. For the pattern "cat", the lines "cat_", "cat1" and "_cat" are all rejected. "cat", "(cat)" and "cat-dog" are accepted, because parentheses and a hyphen are not word characters.
    • Edges of the line. A match at position 0, or one that ends exactly at the end of the line, has no neighbour on that side. Treat it as a boundary instead of reading outside the line.
    • Case. The match is case-sensitive, so "Cat" doesn't match the pattern "cat".
    • Substring only. "xcat" contains cat but not as a whole word, so it is rejected.
    • No matches. The result is "", including for an empty list of lines.

    Testing

    Inputs worth trying, with the results the function returns:

    • "cat" on ["cat sat", "concat", "the cat", "category"] gives "cat sat\nthe cat".
    • "cat" on ["concat cat"] gives "concat cat".
    • "cat" on ["cat", "cat_", "cat1", "_cat", "(cat)", "cat-dog", "Cat"] gives "cat\n(cat)\ncat-dog".
    • "dog" on ["a cat, a dog"] gives "a cat, a dog".
    • "cat" on ["xcat"] 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