Start learning free

LESSON 16 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -w in Go: Whole Word Match with regexp and \b

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:

func 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 "".


Go's regexp package supports the \b word-boundary anchor. Wrap the pattern itself with regexp.QuoteMeta to escape any regex metacharacters.

re := regexp.MustCompile("\\b" + regexp.QuoteMeta(pattern) + "\\b")
// per line: if re.MatchString(line) keep


The full solution:
func grepWord(lines []string, pattern string) string {
    result := []string{}
    re := regexp.MustCompile("\\b" + regexp.QuoteMeta(pattern) + "\\b")
    for i := 0; i < len(lines); i++ {
        if re.MatchString(lines[i]) {
            result = append(result, lines[i])
        }
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 6
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in Go, explained

    Problem overview

    The function grepWord(lines []string, pattern string) string is the -w flag of Unix grep. The pattern is a single word made of letters, digits and underscores, and a line is selected only if it contains the pattern as a whole word: the character just before the match and the one just after it must not be word characters. The match is case-sensitive. The selected lines are joined by newline characters (\n), and the result is "" when none match.

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

    Approach

    A plain strings.Contains can't tell cat in the cat from cat in concat. And checking just the first occurrence isn't enough either, since a line may have a bad occurrence before a good one. A regular expression solves both problems at once.

    The key is \b, a word boundary. It matches a position, not a character: the spot between a word character and a non-word character, or between a word character and the start or end of the text. Surrounding the pattern with it gives \bcat\b, which matches cat only when it is not glued to other word characters. Go's regexp package searches the whole line for any such match, so every occurrence gets a chance.

    The pattern text goes into the regular expression, so characters with a special meaning in a regex would change it. regexp.QuoteMeta escapes them, making the pattern literal. Without it, a pattern such as a.b would match axb, because . stands for any character.

    Step by step

    1. Create the empty result slice for the selected lines.
    2. Build the regular expression once. regexp.MustCompile("\\b" + regexp.QuoteMeta(pattern) + "\\b") glues the boundary markers around the escaped pattern. MustCompile panics if the expression is invalid; with a quoted pattern that can't happen. The expression is compiled before the loop because compiling is much more expensive than matching.
    3. Loop over the positions with for i := 0; i < len(lines); i++.
    4. Test the line. re.MatchString(lines[i]) is true if the expression matches anywhere in the line.
    5. Keep the line with append, storing the grown slice back in result.
    6. Join with newlines and return.

    The solution in Go

    func grepWord(lines []string, pattern string) string {
        result := []string{}
        re := regexp.MustCompile("\\b" + regexp.QuoteMeta(pattern) + "\\b")
        for i := 0; i < len(lines); i++ {
            if re.MatchString(lines[i]) {
                result = append(result, lines[i])
            }
        }
        return strings.Join(result, "\n")
    }
    

    Go details that matter here:

    • Backslashes in strings. In an ordinary Go string, \ starts an escape such as \n, so a literal backslash is written \\. The string "\\b" is therefore the two characters \b, which the regex engine reads as a word boundary. A raw string in backticks, `\b`, gives the same two characters without doubling.
    • \b uses ASCII word characters. In Go's regexp, a word character is a letter, digit or underscore from ASCII, which is exactly what the lesson asks for. The underscore counts, so my_var is not a whole word inside my_var2.
    • The regex is not anchored. MatchString looks for a match anywhere in the line, so the lines don't need to start or end with the pattern.
    • The compiled *regexp.Regexp is reusable. The same re is applied to every line.

    Complexity

    Time: O(n * m), where n is the total length of the lines and m the length of the expression. Go's regular expressions use an engine that doesn't backtrack, so the running time stays linear in the text for a fixed expression. Space: O(m + k): the compiled expression, plus the result slice and the joined output of size k.

    Edge cases and common mistakes

    • Underscores and digits count as word characters. With pattern "my_var", the lines "my_var2" and "my_var_" are rejected, while "(my_var)" and "x-my_var-y" are selected. Likewise, with "cat", the lines "a1cat" and "cat9" are rejected and "cat" is selected.
    • Punctuation is a boundary. "cat." is selected for the pattern "cat".
    • Case matters. The line "Cat" isn't selected for "cat".
    • Skipping QuoteMeta. Without it, the pattern "a.b" becomes the expression \ba.b\b, which matches "axb". With it, only the line "a.b" is selected from ["a.b", "axb"].
    • Forgetting to double the backslash. In a normal Go string, "\b" written with a single backslash is valid: it is the backspace character, one byte. The code compiles, but the expression then looks for literal backspace characters around the pattern, so "the cat" doesn't match and the function returns "" for the lesson's example. That is why the solution writes "\\b".
    • No match. ["cat"] with the pattern "dog" gives "".

    Testing

    • ["cat sat", "concat", "the cat", "category"] with "cat" gives "cat sat\nthe cat".
    • ["concat cat", "concat"] with "cat" gives "concat cat".
    • ["my_var2", "my_var", "(my_var)", "x-my_var-y", "my_var_"] with "my_var" gives "my_var\n(my_var)\nx-my_var-y".
    • ["a.b", "axb"] with "a.b" gives "a.b".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free