Start learning free

LESSON 616 OF 673 · PROJECTS: COMMAND-LINE TOOLS

Whole-Word grep in Python with re 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:

def grepWord(self, lines: List[str], pattern: str) -> str:

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 a regular expression with the \b word-boundary anchor on each side of the pattern. re.escape(pattern) protects against pattern characters that have regex meaning.

Compile once, reuse for every line:
regex = re.compile(r"\b" + re.escape(pattern) + r"\b")
# per line: if regex.search(line): keep


The full solution:
import re

class Solution:
    def grepWord(self, lines, pattern):
        result = []
        regex = re.compile(r"\b" + re.escape(pattern) + r"\b")
        for line in lines:
            if regex.search(line):
                result.append(line)
        return "\n".join(result)

STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in Python, explained

    Problem overview

    This version adds the -w flag of grep. The method grepWord(self, lines, pattern) returns the lines that contain pattern as a whole word, joined with newline characters. The pattern is one word made of letters, digits and underscores. A match counts only when the characters just before and just after it are not word characters (letters, digits or underscores). 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 cat follows the letter n, and "category" because cat is followed by e. A line is kept if at least one occurrence is a whole word, so "concat cat" is kept for its second cat. No match gives "".

    Approach: a regular expression with word boundaries

    A plain in test can't tell cat from the cat inside concat, and checking the neighbours by hand gets awkward when a line holds several occurrences. A regular expression expresses the rule directly. The token \b matches a word boundary: the spot between a word character and a non-word character, or between a word character and the edge of the line. Putting \b on both sides of the pattern makes it match only as a whole word.

    The pattern text must be inserted literally, so any special character in it, such as ., means itself. re.escape does that by putting a backslash before such characters.

    import re
    print(bool(re.search(r"\b" + "a.b" + r"\b", "axb")))
    print(bool(re.search(r"\b" + re.escape("a.b") + r"\b", "axb")))
    print(re.escape("a.b*"))
    
    True
    False
    a\.b\*
    

    Without re.escape, the dot in "a.b" matches any character, so "axb" is wrongly accepted.

    Step by step

    1. Create the empty list result.
    2. Build regex once, before the loop, with re.compile(r"\b" + re.escape(pattern) + r"\b"). The compiled object can be reused for every line. The strings carry an r before the quotes so Python keeps each backslash as written.
    3. Loop over lines.
    4. Test regex.search(line). It scans the whole line and returns a match object when some occurrence is a whole word, or None when none is. A match object counts as true and None as false, so it works directly as the condition.
    5. Append line inside the if.
    6. Return "\n".join(result), which is "" when no line matched.

    The solution in Python

    import re
    
    class Solution:
        def grepWord(self, lines, pattern):
            result = []
            regex = re.compile(r"\b" + re.escape(pattern) + r"\b")
            for line in lines:
                if regex.search(line):
                    result.append(line)
            return "\n".join(result)
    

    The r prefix matters. In an ordinary string, "\b" is the backspace character, a single character, not the two characters that the regex engine needs. The raw string r"\b" keeps the backslash and the b: "\bcat\b" has length 5, while r"\bcat\b" has length 7.

    search looks for a match anywhere in the line. That is different from re.match, which only tries at the start, and from re.fullmatch, which needs the whole line to match. Only search keeps "the cat".

    Underscores and digits count as word characters, so cat_x is rejected for cat, while a hyphen is not a word character and cat-x is accepted.

    Complexity

    Compiling the regex costs time proportional to the pattern length, once. Each search then scans one line, so the total time is about linear in the total length of the lines. Extra space is the list of kept lines and the compiled pattern.

    Edge cases and common mistakes

    • Forgetting re.escape. A pattern such as "a.b" would also accept "axb".
    • Forgetting the raw string. "\b" without the r is a backspace and nothing matches as intended.
    • Using match instead of search. It only checks the start of the line.
    • Several occurrences. "concat cat" is kept, since one whole-word occurrence is enough.
    • Forgetting import re at the top of the file, above the class.
    • Case. "Cat" doesn't match the pattern "cat".

    Testing

    With pattern = "cat", the lines ["cat sat", "concat", "the cat", "category", "concat cat", "cat_x", "cat-x", "cat"] give:

    'cat sat\nthe cat\nconcat cat\ncat-x\ncat'
    

    With pattern = "a.b" and ["a.b", "a.bc", "axb"] only "a.b" is returned, because the dot is matched literally.

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