Start learning free

LESSON 16 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep -w in Kotlin: Whole Word Match with Regex

Practice Read the full explanation

Build the -w flag of the Unix grep command. Given a list of lines and a search pattern (a single word made of letters, digits, and underscores), return all lines that contain pattern as a WHOLE word — i.e. the characters immediately before and after the match must NOT be word characters (letters, digits, or underscores). The match is case-sensitive.

Return the matching lines joined by newline characters (\n).

Function signature:

fun grepWord(lines: List<String>, pattern: String): String

Example:

Input:
pattern = "cat"
lines = ["cat sat", "concat", "the cat", "category"]

Output: "cat sat\nthe cat"

When printed:
cat sat
the cat

Notice that "concat" is rejected because cat is preceded by the word character n (con|cat), and "category" is rejected because cat is followed by the word character e.

A line may contain the pattern more than once. It is selected if at least one occurrence is a whole word: with pattern "cat", the line "concat cat" is selected because of its second cat. The lines contain only ASCII characters.

If no lines match, return the empty string "".


Kotlin's Regex supports the \b word-boundary anchor. Wrap the pattern itself with Regex.escape to escape any regex metacharacters.

val regex = Regex("\\b" + Regex.escape(pattern) + "\\b")
// per line: if (regex.containsMatchIn(line)) keep


The full solution:
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")
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in Kotlin, explained

    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

    1. Create the result list in a val named result with mutableListOf<String>().
    2. Build the regex once. A val named regex holds Regex(...), made from \b, then Regex.escape(pattern), then \b again. Each backslash is written twice inside a Kotlin string.
    3. Loop over the lines with for (line in lines), closing the brace right away.
    4. Test the line. regex.containsMatchIn(line) is true when the regex matches anywhere in the text. One whole-word match anywhere in the line is enough to keep it.
    5. Keep the line. Inside the if, result.add(line).
    6. 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, so Regex("\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 text a.b. Without it, the . would match any character, and the pattern a.b would also match axb. This lesson's patterns are only word characters, but escaping is a good habit whenever user text goes into a regex.
    • containsMatchIn versus matches. containsMatchIn looks for the regex anywhere in the text. matches would 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 to Regex.

    Edge cases and common mistakes

    • Underscores and digits are word characters. cat_1 and cat1 don't contain cat as a whole word. A hyphen or a parenthesis isn't a word character, so cat-1 and (cat) do match.
    • Repeated occurrences. containsMatchIn keeps looking after a failed attempt, so "concat cat" is found through its second occurrence.
    • Case. "Cat" doesn't match cat.
    • Only a left or only a right boundary. Leaving off one \b would accept category or concat.
    • Cost. Building a Regex inside 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:

    linespatternresult
    ["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
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free