Start learning free

LESSON 14 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep v2 in Scala: Case-Insensitive Match with toLowerCase

Practice Read the full explanation

Build the -i flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring, ignoring letter case. Return the matching lines joined by newline characters (\n).

Function signature:

def grepCaseInsensitive(lines: Array[String], pattern: String): String

Example:

Input:
pattern = "ERR"
lines = ["Error: 1", "ok"]

Output: "Error: 1"

When printed:
Error: 1

The matching is case-insensitive but the original line (preserving its original casing) is returned. If no lines match, return the empty string "". The lines contain only ASCII characters.


Lowercase the pattern once, then for each line check line.toLowerCase().contains(lowerPattern). Collect the ORIGINAL line on a hit.

The full solution:
class Solution {
    def grepCaseInsensitive(lines: Array[String], pattern: String): String = {
        val result = scala.collection.mutable.ArrayBuffer[String]()
        val lowerPattern = pattern.toLowerCase()
        for (line <- lines) {
            if (line.toLowerCase().contains(lowerPattern)) {
                result += line
            }
        }
        return result.mkString("\n")
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in Scala, explained

    Problem overview

    This version adds the -i flag of grep. grepCaseInsensitive(lines: Array[String], pattern: String): String returns every line that contains pattern as a substring, ignoring letter case, joined by \n. The lines come back exactly as they were, with their original capitals. If nothing matches, the result is "". The lines are plain ASCII.

    With pattern = "ERR" and lines = ["Error: 1", "ok"], the first line matches even though ERR and Err differ in case, so the result is "Error: 1", capital E included.

    Approach

    The previous version already filters lines with contains. The only new idea is how to ignore case: compare in one case. Convert the pattern to lowercase, convert each line to lowercase just for the test, and keep the original line if the test passes.

    Two details shape the code:

    • The lowercase pattern never changes, so it is computed once before the loop, not again for every line.
    • The lowercase copy of a line is only used for checking. What goes into the result is the original line, so the output keeps its capitals. Strings are immutable in Scala, so toLowerCase() returns a new string and leaves line untouched.

    With pattern = "ERR" the lowercase pattern is "err". The line "eRRor 2" becomes "error 2", which contains it, and the original "eRRor 2" is the one that is kept.

    Step by step

    1. Create the buffer. A val named result holds an empty scala.collection.mutable.ArrayBuffer[String].
    2. Lowercase the pattern once into a val named lowerPattern, with pattern.toLowerCase().
    3. Loop over the lines with for (line <- lines).
    4. Compare in lowercase. The if checks whether line.toLowerCase() contains lowerPattern. Both sides are lowercase now, so ERR finds Error.
    5. Keep the original line. Append line (not the lowercase copy) to result with +=.
    6. Join and return with result.mkString("\n").

    The solution in Scala

    class Solution {
        def grepCaseInsensitive(lines: Array[String], pattern: String): String = {
            val result = scala.collection.mutable.ArrayBuffer[String]()
            val lowerPattern = pattern.toLowerCase()
            for (line <- lines) {
                if (line.toLowerCase().contains(lowerPattern)) {
                    result += line
                }
            }
            return result.mkString("\n")
        }
    }
    

    Language details:

    • toLowerCase() is a Java String method that returns a new string. The original is never changed, which is why appending line keeps the capitals.
    • Lowercasing both sides works for ASCII text, the input this lesson promises. Case rules for other alphabets are more complicated, so ignoring case in general text takes more care.
    • mkString("\n") puts a newline between lines only, and returns "" for an empty buffer.
    • val lowerPattern is a constant for the whole call, so val is the right choice.

    Complexity

    Each line is lowercased and searched once, so the time is proportional to the total size of the input (times the pattern length in the worst case for the search). Each lowercase copy is temporary, so the extra space is the result buffer, at most one reference per input line, plus one line-sized copy at a time.

    Edge cases and common mistakes

    • Appending the lowercase copy. The result would have lost its capitals: "Error: 1" would come back as "error: 1".
    • Lowercasing only one side. If the pattern stays "ERR" but the line is lowercased, nothing can match, because a lowercase line has no capital letters.
    • Lowercasing the pattern inside the loop. It works but repeats the same conversion for every line.
    • No matches. The buffer stays empty and the result is "".

    Testing

    linespatternResult
    Array("Error: 1", "ok", "eRRor 2")"ERR""Error: 1\neRRor 2"
    Array("Error: 1")"xyz"""
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free