Start learning free

LESSON 16 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep -w in TypeScript: Whole-Word Match with RegExp

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:

grepWord(lines: 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 "".


TypeScript's RegExp supports the \b word boundary anchor. Build the regex once outside the loop, then use regex.test(line).

let regex = new RegExp("\\b" + pattern + "\\b");
// per line: if (regex.test(line)) keep


The full solution:
class Solution {
    grepWord(lines: string[], pattern: string): string {
        let result: string[] = [];
        let regex = new RegExp("\\b" + pattern + "\\b");
        for (let i = 0; i < lines.length; i++) {
            if (regex.test(lines[i])) {
                result.push(lines[i]);
            }
        }
        return result.join("\n");
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in TypeScript, explained

    Problem overview

    This version builds the -w flag of grep. grepWord(lines: string[], pattern: string): string returns the lines that contain pattern as a whole word, joined by newline characters. The pattern is a single word made of letters, digits and underscores. A match is a whole word when the characters just before and just after it are not word characters (letters, digits or underscores). The match is case-sensitive, and if nothing matches the result is "".

    With pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". "concat" is rejected because cat is preceded by the word character n, and "category" is rejected because it is followed by e. A line is selected if at least one occurrence is a whole word, so "concat cat" is selected for its second cat.

    Approach: a regular expression with word boundaries

    A plain includes cannot tell cat from concat. One option is to find each occurrence with indexOf and inspect the characters around it, which needs care for matches at the start or end of a line and for lines with several occurrences. A regular expression does all of that in one pattern.

    The regular expression token \b is a word boundary: the position between a word character and a non-word character, or the edge of the text next to a word character. Putting \b on both sides of the pattern gives \bcat\b, which matches cat only when it is a whole word. It matches inside the cat and not inside concat or category. If a line has several occurrences, the regular expression engine tries each one, so a later whole-word match is still found.

    Step by step

    1. Create the result as an empty string[].
    2. Build the regex. new RegExp("\\b" + pattern + "\\b") creates a regular expression from a string. Inside a TypeScript string a backslash must be doubled, so "\\b" reaches the regex engine as \b. The pattern has only letters, digits and underscores, so it needs no escaping. Build the regex once, before the loop.
    3. Loop by position with i from 0 while i < lines.length.
    4. Test the line. regex.test(lines[i]) returns true when the regex matches anywhere in the line. One whole-word match is enough.
    5. Keep the line with result.push(lines[i]).
    6. Join and return with result.join("\n").

    The solution in TypeScript

    class Solution {
        grepWord(lines: string[], pattern: string): string {
            let result: string[] = [];
            let regex = new RegExp("\\b" + pattern + "\\b");
            for (let i = 0; i < lines.length; i++) {
                if (regex.test(lines[i])) {
                    result.push(lines[i]);
                }
            }
            return result.join("\n");
        }
    }

    Details that matter:

    • Doubling the backslash. In an ordinary string, "\b" is a single backspace character, with length 1. "\\b" is two characters, a backslash and a b, which is what the regex needs. Writing "\b" by mistake silently builds a regex that looks for a backspace character and matches nothing useful.
    • Underscore and digits count as word characters. With "cat", the line "cat_1" is not selected and "cat9" is not selected, but "cat-1" is, because - is not a word character.
    • Case. The regex has no i flag, so /\bcat\b/ does not match "Cat".
    • Escaping. Because the pattern holds only word characters, building the regex from it directly is safe. If the pattern could contain characters such as ., they would act as regex operators: new RegExp("\\ba.b\\b") matches "axb".
    • No g flag. A regex created with the g flag remembers where it stopped, so calling test repeatedly on it gives alternating results: [true, false, true] for three calls on "cat". This regex has no flags, so each call starts at the beginning of the line.

    Complexity

    The regex is compiled once. Each line is scanned once, so the time is proportional to the total length of the lines (for a simple literal pattern like this one). The result array can hold all the lines, so the extra space is up to the size of the input.

    Edge cases and common mistakes

    • Match inside a longer word. "concat" and "category" must not match cat.
    • Several occurrences. ["concat cat"] is selected, because the second cat is a whole word even though the first is not.
    • Punctuation next to the word. A space, a hyphen, a plus sign or the edge of the line all count as boundaries. For example ["a+b"] with "a" is selected.
    • A single backslash. "\b" + pattern + "\b" is the classic bug described above.
    • No match or empty list. The result is "".

    Testing

    linespatternResult
    ["cat sat", "concat", "the cat", "category"]"cat""cat sat\nthe cat"
    ["concat cat"]"cat""concat cat"
    ["cat_1", "cat-1", "cat"]"cat""cat-1\ncat"
    ["cat9"]"cat"""

    The next version builds on this one.

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