Start learning free

LESSON 388 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v4 — Whole Word Match in Rust

Practice

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

    Grep V4 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free