Start learning free

LESSON 384 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v4 — Whole Word Match in Python

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:

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

    Grep V4 in Python

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