Start learning free

LESSON 16 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -w in C#: Whole-Word Matching with Regex

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:

public string GrepWord(List<string> lines, string pattern)

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


Use System.Text.RegularExpressions.Regex with \b word-boundary anchors. Wrap the pattern itself with Regex.Escape to escape any regex metacharacters.

Regex regex = new Regex("\\b" + Regex.Escape(pattern) + "\\b");
// per line: if (regex.IsMatch(line)) keep


The full solution:
class Solution {
    public string GrepWord(List<string> lines, string pattern) {
        List<string> result = new List<string>();
        Regex regex = new Regex("\\b" + Regex.Escape(pattern) + "\\b");
        foreach (string line in lines) {
            if (regex.IsMatch(line)) {
                result.Add(line);
            }
        }
        return string.Join("\n", result);
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in C#, explained

    Problem overview

    GrepWord is the -w flag of grep. It takes a List<string> named 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 by \n: the characters just before and just after the match must not be word characters. The match is case-sensitive.

    For pattern "cat" and lines ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". "concat" has n in front of cat, and "category" has e after it. A line with several occurrences is kept if at least one is a whole word, so "concat cat" is kept for the second cat.

    Approach

    Contains is not enough here: it would accept "concat". You could look at the characters around each occurrence by hand, but you would have to handle several occurrences per line and the edges of the line. A regular expression handles all of this in one pattern.

    In a regex, \b is a word boundary: a position between a word character and a non-word character, or between a word character and the start or end of the text. Placing \b on both sides of the word, as in \bcat\b, matches cat only when it stands alone. The regex finds a match anywhere in the line, and any one match is enough to keep it.

    The pattern comes from the caller, so it is passed through Regex.Escape, which turns special characters into literal text. Otherwise a character such as + or . in the pattern would be read as regex syntax.

    Step by step

    1. Create result, an empty List<string>.
    2. Build regex, a Regex, from \b, the escaped pattern and another \b. In a normal C# string literal each backslash is written twice, so \b becomes "\\b". It is built once, before the loop, because it is the same for every line.
    3. Loop over lines with foreach.
    4. Test with regex.IsMatch(line). It is true when the regex matches anywhere in the line.
    5. Add the line to result.
    6. Return string.Join("\n", result).

    The solution in C#

    class Solution {
        public string GrepWord(List<string> lines, string pattern) {
            List<string> result = new List<string>();
            Regex regex = new Regex("\\b" + Regex.Escape(pattern) + "\\b");
            foreach (string line in lines) {
                if (regex.IsMatch(line)) {
                    result.Add(line);
                }
            }
            return string.Join("\n", result);
        }
    }
    

    The details worth knowing:

    • The using line. Regex lives in System.Text.RegularExpressions. A file that uses it needs using System.Text.RegularExpressions; at the top.
    • Doubled backslashes. In "\\b" the string holds a backslash and a b, which is what the regex engine wants. A single "\b" would be a backspace character, which is a different thing. A verbatim string, @"\b", is an equivalent way to write it without doubling.
    • Why escape. With pattern "a+b", the unescaped regex \ba+b\b matches "aab", because + means "one or more". Regex.Escape("a+b") produces a\+b, which matches the literal text. For "a+b is" the escaped version keeps the line, and for "aab" it does not.
    • Word characters are letters, digits and the underscore. So "a_cat" and "cat1" do not match cat, but "cat." and "the cat!" do, because punctuation is not a word character.
    • One regex, many lines. A Regex object can be reused, so building it once saves repeating the setup for each line.

    Complexity

    Let n be the number of lines and m the longest line length. Time: the engine scans each line looking for the word with its boundaries, roughly n times m for a literal word like this. Space: the compiled regex, the result list and the joined string.

    Edge cases and common mistakes

    • Using Contains. It would keep "concat" and "category".
    • Checking only the first occurrence. With a hand-written loop using IndexOf, "concat cat" is easy to reject by mistake. The regex tries every position.
    • Single backslashes. "\b" in a normal string is a backspace character, so the regex would look for a backspace, not a boundary, and nothing would match. Write "\\b" or use a verbatim string.
    • Skipping Regex.Escape. It matters for patterns that contain regex symbols, and it costs nothing for plain words.
    • Case. "Cat" does not match pattern "cat".
    • Line edges. "cat" alone, "cat sat" and "the cat" all match, because the start and end of the line count as boundaries.

    Testing

    • Pattern "cat" with ["cat sat", "concat", "the cat", "category"] gives "cat sat\nthe cat".
    • Pattern "cat" with ["concat cat", "a_cat", "cat1", "cat."] gives "concat cat\ncat.".
    • Pattern "a+b" with ["a+b is", "a+bc", "x a+b"] gives "a+b is\nx a+b".
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free