Start learning free

LESSON 16 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep v4 in Scala: Whole Word Match with a 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:

def 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 "".


Use java.util.regex.Pattern with \b word-boundary anchors. Wrap the pattern itself with Pattern.quote to escape any regex metacharacters.

val regex = java.util.regex.Pattern.compile(
    "\\b" + java.util.regex.Pattern.quote(pattern) + "\\b"
)
// per line: if (regex.matcher(line).find()) keep


The full solution:
class Solution {
    def grepWord(lines: List[String], pattern: String): String = {
        var result = scala.collection.mutable.ListBuffer[String]()
        val regex = java.util.regex.Pattern.compile("\\b" + java.util.regex.Pattern.quote(pattern) + "\\b")
        for (line <- lines) {
            if (regex.matcher(line).find()) {
                result += line
            }
        }
        result.mkString("\n")
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in Scala, explained

    Problem overview

    This version adds the -w flag of grep. grepWord(lines: List[String], pattern: String): String returns the lines that contain pattern as a whole word, joined by \n. 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 are not word characters (letters, digits or underscores), or when the match touches the start or end of the line. The match is case-sensitive, and the lines are plain ASCII.

    With pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". The line "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. With "cat", the line "concat cat" is selected because of its second cat, even though the first one is inside concat. If no line matches, the result is "".

    Approach

    A plain contains can't tell cat from concat, since both contain the letters. Checking the neighbouring characters by hand is possible, but it needs care at the ends of the line and with lines where the pattern occurs several times. A regular expression does this directly, thanks to the word boundary \b.

    \b matches a position, not a character: the spot between a word character and a non-word character, or at the edge of the text next to a word character. The regex \bcat\b therefore matches cat in "the cat" and in "cat-dog" (a hyphen is not a word character), but not in "concat", "category" or "cat_dog" (an underscore is a word character).

    One more precaution: the pattern is inserted into the regex, so any special character in it would be read as regex syntax. Pattern.quote wraps the text so that it is matched literally. For a pattern made of letters, digits and underscores this changes nothing, but it keeps the regex safe whatever the pattern holds.

    The regex is built once, before the loop, and then tried on each line with find(), which looks for a match anywhere in the line. As soon as any occurrence is a whole word, find() returns true, so repeated occurrences are handled for free.

    Step by step

    1. Create the buffer. A val named result holds the growing list of matching lines. The reference solution uses a var holding a ListBuffer, which would also work as a val, since it is never reassigned.
    2. Build the regex once. Compile "\\b", then Pattern.quote(pattern), then "\\b" with java.util.regex.Pattern.compile. In a Scala string the backslash is written twice.
    3. Loop over the lines with for (line <- lines).
    4. Test the line. regex.matcher(line) creates a matcher for this line, and find() is true when the regex matches anywhere in it.
    5. Keep the match. Append line to the buffer with +=.
    6. Join and return with result.mkString("\n").

    The solution in Scala

    class Solution {
        def grepWord(lines: List[String], pattern: String): String = {
            var result = scala.collection.mutable.ListBuffer[String]()
            val regex = java.util.regex.Pattern.compile("\\b" + java.util.regex.Pattern.quote(pattern) + "\\b")
            for (line <- lines) {
                if (regex.matcher(line).find()) {
                    result += line
                }
            }
            result.mkString("\n")
        }
    }
    

    Language details:

    • Scala code can use Java's library directly. java.util.regex.Pattern is Java's regex class, written here with its full name.
    • The two "\\b" literals contain a backslash and a b. If they were written "\b", Scala would read that as a backspace character, not a word boundary.
    • ListBuffer is another growable mutable collection, much like ArrayBuffer; += appends to it.
    • The last expression, result.mkString("\n"), is the method's value, so no return is needed. In Scala the last expression of a block is its value.
    • The var is never reassigned, so val would express the intent better.

    Complexity

    The regex is compiled once. Each line is then scanned once by the matcher, so the time is roughly proportional to the total size of the input. The buffer holds at most one reference per line, so the extra space is O(n) plus the result string.

    Edge cases and common mistakes

    • Using contains. It would accept concat and category.
    • Checking only the first occurrence. "concat cat" must be selected. The regex approach finds the later whole-word occurrence on its own.
    • Treating underscores as separators. "cat_dog" is not a match for cat, because _ is a word character. A hyphen or a dot, on the other hand, ends a word.
    • Single backslashes. Without doubling them in the Scala string, the boundary markers don't mean what you intend.
    • Skipping Pattern.quote. A pattern containing . would match any character. With the quote, the pattern a.b matches only a literal dot.
    • Case. The match is case-sensitive, so "Cat" is not a match for cat.

    Testing

    linespatternResult
    List("cat sat", "concat", "the cat", "category")"cat""cat sat\nthe cat"
    List("concat cat", "cat_dog", "cat-dog", "Cat")"cat""concat cat\ncat-dog"
    List("a.b", "axb", "a.b.")"a.b""a.b\na.b."
    List("x")"z"""
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free