Problem overview
GrepWord is the -w flag of grep. It takes a List<string> named lines and a pattern that is a single word made of letters, digits and underscores. It returns the lines that contain the pattern as a whole word, joined by \n: the characters just before and just after the match must not be word characters. The match is case-sensitive.
For pattern "cat" and lines ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". "concat" has n in front of cat, and "category" has e after it. A line with several occurrences is kept if at least one is a whole word, so "concat cat" is kept for the second cat.
Approach
Contains is not enough here: it would accept "concat". You could look at the characters around each occurrence by hand, but you would have to handle several occurrences per line and the edges of the line. A regular expression handles all of this in one pattern.
In a regex, \b is a word boundary: a position between a word character and a non-word character, or between a word character and the start or end of the text. Placing \b on both sides of the word, as in \bcat\b, matches cat only when it stands alone. The regex finds a match anywhere in the line, and any one match is enough to keep it.
The pattern comes from the caller, so it is passed through Regex.Escape, which turns special characters into literal text. Otherwise a character such as + or . in the pattern would be read as regex syntax.
Step by step
- Create
result, an emptyList<string>. - Build
regex, aRegex, from\b, the escaped pattern and another\b. In a normal C# string literal each backslash is written twice, so\bbecomes"\\b". It is built once, before the loop, because it is the same for every line. - Loop over
lineswithforeach. - Test with
regex.IsMatch(line). It is true when the regex matches anywhere in the line. - Add the line to
result. - Return
string.Join("\n", result).
The solution in C#
class Solution {
public string GrepWord(List<string> lines, string pattern) {
List<string> result = new List<string>();
Regex regex = new Regex("\\b" + Regex.Escape(pattern) + "\\b");
foreach (string line in lines) {
if (regex.IsMatch(line)) {
result.Add(line);
}
}
return string.Join("\n", result);
}
}
The details worth knowing:
- The
usingline.Regexlives inSystem.Text.RegularExpressions. A file that uses it needsusing System.Text.RegularExpressions;at the top. - Doubled backslashes. In
"\\b"the string holds a backslash and ab, which is what the regex engine wants. A single"\b"would be a backspace character, which is a different thing. A verbatim string,@"\b", is an equivalent way to write it without doubling. - Why escape. With pattern
"a+b", the unescaped regex\ba+b\bmatches"aab", because+means "one or more".Regex.Escape("a+b")producesa\+b, which matches the literal text. For"a+b is"the escaped version keeps the line, and for"aab"it does not. - Word characters are letters, digits and the underscore. So
"a_cat"and"cat1"do not matchcat, but"cat."and"the cat!"do, because punctuation is not a word character. - One regex, many lines. A
Regexobject can be reused, so building it once saves repeating the setup for each line.
Complexity
Let n be the number of lines and m the longest line length. Time: the engine scans each line looking for the word with its boundaries, roughly n times m for a literal word like this. Space: the compiled regex, the result list and the joined string.
Edge cases and common mistakes
- Using
Contains. It would keep"concat"and"category". - Checking only the first occurrence. With a hand-written loop using
IndexOf,"concat cat"is easy to reject by mistake. The regex tries every position. - Single backslashes.
"\b"in a normal string is a backspace character, so the regex would look for a backspace, not a boundary, and nothing would match. Write"\\b"or use a verbatim string. - Skipping
Regex.Escape. It matters for patterns that contain regex symbols, and it costs nothing for plain words. - Case.
"Cat"does not match pattern"cat". - Line edges.
"cat"alone,"cat sat"and"the cat"all match, because the start and end of the line count as boundaries.
Testing
- Pattern
"cat"with["cat sat", "concat", "the cat", "category"]gives"cat sat\nthe cat". - Pattern
"cat"with["concat cat", "a_cat", "cat1", "cat."]gives"concat cat\ncat.". - Pattern
"a+b"with["a+b is", "a+bc", "x a+b"]gives"a+b is\nx a+b".
