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
- Create the empty
resultslice for the selected lines. - Build the regular expression once.
regexp.MustCompile("\\b" + regexp.QuoteMeta(pattern) + "\\b")glues the boundary markers around the escaped pattern.MustCompilepanics 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. - Loop over the positions with
for i := 0; i < len(lines); i++. - Test the line.
re.MatchString(lines[i])is true if the expression matches anywhere in the line. - Keep the line with
append, storing the grown slice back inresult. - 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. \buses ASCII word characters. In Go'sregexp, a word character is a letter, digit or underscore from ASCII, which is exactly what the lesson asks for. The underscore counts, somy_varis not a whole word insidemy_var2.- The regex is not anchored.
MatchStringlooks for a match anywhere in the line, so the lines don't need to start or end with the pattern. - The compiled
*regexp.Regexpis reusable. The samereis 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".
