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
- Create the empty list
result. - Build
regexonce, before the loop, withre.compile(r"\b" + re.escape(pattern) + r"\b"). The compiled object can be reused for every line. The strings carry anrbefore the quotes so Python keeps each backslash as written. - Loop over
lines. - Test
regex.search(line). It scans the whole line and returns a match object when some occurrence is a whole word, orNonewhen none is. A match object counts as true andNoneas false, so it works directly as the condition. - Append
lineinside theif. - 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 theris a backspace and nothing matches as intended. - Using
matchinstead ofsearch. It only checks the start of the line. - Several occurrences.
"concat cat"is kept, since one whole-word occurrence is enough. - Forgetting
import reat 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.
