Problem overview
This version adds the -w flag. The function grepWord(lines: List<String>, pattern: String): String returns every line that contains pattern as a whole word, joined by newline characters. The pattern is a single word made of letters, digits and underscores. A match counts as a whole word when the characters just before and just after it aren't 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" fails because cat is preceded by the letter n, and "category" fails because it is followed by e.
A line can contain the pattern several times. It is selected if at least one occurrence is a whole word, so "concat cat" is selected because of its second cat. No match gives the empty string.
Approach: a regular expression with word boundaries
A plain contains can't tell cat from concat. You could look at the characters around each occurrence by hand, but a regular expression says it directly. 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. Writing \bcat\b means "cat with a boundary on each side", which matches in the cat and doesn't match inside concat or category.
Two more pieces make it safe. The pattern is inserted into the regex, so any special character in it must be treated as plain text: Regex.escape(pattern) does that. And a Regex object is built once before the loop and reused for every line.
Step by step
- Create the result list in a
valnamedresultwithmutableListOf<String>(). - Build the regex once. A
valnamedregexholdsRegex(...), made from\b, thenRegex.escape(pattern), then\bagain. Each backslash is written twice inside a Kotlin string. - Loop over the lines with
for (line in lines), closing the brace right away. - Test the line.
regex.containsMatchIn(line)istruewhen the regex matches anywhere in the text. One whole-word match anywhere in the line is enough to keep it. - Keep the line. Inside the
if,result.add(line). - Join and return with
result.joinToString("\n"). An empty result gives the empty string.
The solution in Kotlin
class Solution {
fun grepWord(lines: List<String>, pattern: String): String {
val result = mutableListOf<String>()
val regex = Regex("\\b" + Regex.escape(pattern) + "\\b")
for (line in lines) {
if (regex.containsMatchIn(line)) {
result.add(line)
}
}
return result.joinToString("\n")
}
}
Kotlin details to know:
- Doubled backslashes. In a Kotlin string,
"\\b"is the two characters\b, which the regex engine reads as a word boundary. A single"\b"compiles too, but in a string literal it is the backspace character, soRegex("\bcat\b")finds nothing in"the cat". That is a quiet mistake, because there is no compile error. Regex.escape. For"a.b"it returns\Qa.b\E, which the engine treats as the literal texta.b. Without it, the.would match any character, and the patterna.bwould also matchaxb. This lesson's patterns are only word characters, but escaping is a good habit whenever user text goes into a regex.containsMatchInversusmatches.containsMatchInlooks for the regex anywhere in the text.matcheswould require the entire line to match, which is the wrong question here.- String concatenation.
"\\b" + Regex.escape(pattern) + "\\b"joins three strings with+before they are handed toRegex.
Edge cases and common mistakes
- Underscores and digits are word characters.
cat_1andcat1don't containcatas a whole word. A hyphen or a parenthesis isn't a word character, socat-1and(cat)do match. - Repeated occurrences.
containsMatchInkeeps looking after a failed attempt, so"concat cat"is found through its second occurrence. - Case.
"Cat"doesn't matchcat. - Only a left or only a right boundary. Leaving off one
\bwould acceptcategoryorconcat. - Cost. Building a
Regexinside the loop would work but repeats the same compilation for every line, so the lesson builds it once.
Testing
These results come from running the reference solution:
| lines | pattern | result |
|---|---|---|
["cat sat", "concat", "the cat", "category"] | "cat" | cat sat and the cat, on two lines |
["concat cat", "concat"] | "cat" | concat cat |
["cat_1", "cat-1", "cat1", "(cat)", "cat"] | "cat" | cat-1, (cat) and cat, on three lines |
["Cat", "cat"] | "cat" | cat |
