Problem overview
This version builds the -w flag of grep. grepWord(lines: string[], pattern: string): string returns the lines that contain pattern as a whole word, joined by newline characters. The pattern is a single word made of letters, digits and underscores. A match is a whole word when the characters just before and just after it are not word characters (letters, digits or underscores). The match is case-sensitive, and if nothing matches the result is "".
With pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". "concat" is rejected because cat is preceded by the word character n, and "category" is rejected because it is followed by e. A line is selected if at least one occurrence is a whole word, so "concat cat" is selected for its second cat.
Approach: a regular expression with word boundaries
A plain includes cannot tell cat from concat. One option is to find each occurrence with indexOf and inspect the characters around it, which needs care for matches at the start or end of a line and for lines with several occurrences. A regular expression does all of that in one pattern.
The regular expression token \b is a word boundary: the position between a word character and a non-word character, or the edge of the text next to a word character. Putting \b on both sides of the pattern gives \bcat\b, which matches cat only when it is a whole word. It matches inside the cat and not inside concat or category. If a line has several occurrences, the regular expression engine tries each one, so a later whole-word match is still found.
Step by step
- Create the result as an empty
string[]. - Build the regex.
new RegExp("\\b" + pattern + "\\b")creates a regular expression from a string. Inside a TypeScript string a backslash must be doubled, so"\\b"reaches the regex engine as\b. The pattern has only letters, digits and underscores, so it needs no escaping. Build the regex once, before the loop. - Loop by position with
ifrom 0 whilei < lines.length. - Test the line.
regex.test(lines[i])returnstruewhen the regex matches anywhere in the line. One whole-word match is enough. - Keep the line with
result.push(lines[i]). - Join and return with
result.join("\n").
The solution in TypeScript
class Solution {
grepWord(lines: string[], pattern: string): string {
let result: string[] = [];
let regex = new RegExp("\\b" + pattern + "\\b");
for (let i = 0; i < lines.length; i++) {
if (regex.test(lines[i])) {
result.push(lines[i]);
}
}
return result.join("\n");
}
}
Details that matter:
- Doubling the backslash. In an ordinary string,
"\b"is a single backspace character, with length 1."\\b"is two characters, a backslash and ab, which is what the regex needs. Writing"\b"by mistake silently builds a regex that looks for a backspace character and matches nothing useful. - Underscore and digits count as word characters. With
"cat", the line"cat_1"is not selected and"cat9"is not selected, but"cat-1"is, because-is not a word character. - Case. The regex has no
iflag, so/\bcat\b/does not match"Cat". - Escaping. Because the pattern holds only word characters, building the regex from it directly is safe. If the pattern could contain characters such as
., they would act as regex operators:new RegExp("\\ba.b\\b")matches"axb". - No
gflag. A regex created with thegflag remembers where it stopped, so callingtestrepeatedly on it gives alternating results:[true, false, true]for three calls on"cat". This regex has no flags, so each call starts at the beginning of the line.
Complexity
The regex is compiled once. Each line is scanned once, so the time is proportional to the total length of the lines (for a simple literal pattern like this one). The result array can hold all the lines, so the extra space is up to the size of the input.
Edge cases and common mistakes
- Match inside a longer word.
"concat"and"category"must not matchcat. - Several occurrences.
["concat cat"]is selected, because the secondcatis a whole word even though the first is not. - Punctuation next to the word. A space, a hyphen, a plus sign or the edge of the line all count as boundaries. For example
["a+b"]with"a"is selected. - A single backslash.
"\b" + pattern + "\b"is the classic bug described above. - No match or empty list. The result is
"".
Testing
| lines | pattern | Result |
|---|---|---|
["cat sat", "concat", "the cat", "category"] | "cat" | "cat sat\nthe cat" |
["concat cat"] | "cat" | "concat cat" |
["cat_1", "cat-1", "cat"] | "cat" | "cat-1\ncat" |
["cat9"] | "cat" | "" |
The next version builds on this one.
