Start learning free

LESSON 14 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -i in Java: 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:

public String grepCaseInsensitive(List<String> lines, String pattern)

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). Push the ORIGINAL line on a hit.

The full solution:
class Solution {
    public String grepCaseInsensitive(List<String> lines, String pattern) {
        List<String> result = new ArrayList<>();
        String lowerPattern = pattern.toLowerCase();
        for (String line : lines) {
            if (line.toLowerCase().contains(lowerPattern)) {
                result.add(line);
            }
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in Java, explained

    Problem overview

    The method grepCaseInsensitive takes a List<String> named lines and a search string pattern. It returns every line that contains the pattern as a substring, ignoring letter case, joined by newline characters. The lines come back exactly as they were given, capitals included. If nothing matches, the result is "". The lines contain only ASCII characters.

    For pattern = "ERR" and lines = ["Error: 1", "ok"] the result is "Error: 1". The pattern is upper case and the line has Err, yet they match, and the line is returned with its original casing.

    Approach: compare in one case, return the original

    Substring search with contains is case-sensitive, so to ignore case, both sides of the comparison must be in the same case. Lowercasing both the pattern and the line makes ERR and Err into the same err.

    The key point is what gets stored. The lowercase copy of a line exists only for the test. What goes into the result is the original line. That way the output keeps the capitalization of the input, which is what the real grep -i does.

    The pattern is the same for every line, so it is lowercased once before the loop. The lines differ, so each one is lowercased as it is checked.

    Step by step

    1. Create result, an empty ArrayList declared as a List<String>, for the lines that match.
    2. Lowercase the pattern once into lowerPattern with pattern.toLowerCase(). Doing it here, before the loop, avoids repeating the same work for every line.
    3. Loop over the lines with a for-each loop, naming each entry line.
    4. Test the lowercase line. line.toLowerCase().contains(lowerPattern) checks the substring with both sides in lower case. The line variable itself is not changed.
    5. Add the original line with result.add(line), capitals and all.
    6. Join and return with String.join("\n", result). An empty result joins to "", the answer for no matches.

    The solution in Java

    class Solution {
        public String grepCaseInsensitive(List<String> lines, String pattern) {
            List<String> result = new ArrayList<>();
            String lowerPattern = pattern.toLowerCase();
            for (String line : lines) {
                if (line.toLowerCase().contains(lowerPattern)) {
                    result.add(line);
                }
            }
            return String.join("\n", result);
        }
    }
    

    The Java details worth a closer look:

    • Strings are immutable. toLowerCase() does not change the string it is called on; it returns a new one. That is why line is still the original afterwards and can be added to result unchanged. Writing line.toLowerCase(); as a statement on its own, without using the value, does nothing.
    • The locale. toLowerCase() without arguments follows the default locale of the machine. For ASCII text this makes no difference in almost every locale, but Turkish rules, for example, lowercase I to a dotless ı. toLowerCase(Locale.ROOT) gives the same answer everywhere; for the lesson's ASCII input both work.
    • An alternative. equalsIgnoreCase compares whole strings, not substrings, and there is no containsIgnoreCase in String. Lowercasing both sides is the usual way to get substring search without regular expressions.
    • Imports. A standalone file needs import java.util.*; for List and ArrayList.

    Complexity

    Let n be the number of lines and m the total number of characters in them.

    Time: O(m * p) in the worst case, with p as the pattern length. Lowercasing a line costs its length, and then contains scans it. Lowercasing the pattern costs O(p) once.

    Space: O(n + m). The list holds up to n references, the joined result can hold up to about m characters, and the lowercase copy of one line exists at a time while it is being tested.

    Edge cases and common mistakes

    • Several matches with different casing. ["Error: 1", "eRRor 2", "fine"] with "err" gives "Error: 1\neRRor 2", each line in its own original casing.
    • No match. ["abc"] with "xyz" gives "", and so does an empty list.
    • A pattern that spans a space. ["Hello World", "HELLO"] with "o w" gives "Hello World". Lowercasing treats spaces like any other character.
    • Adding the lowercase line. result.add(line.toLowerCase()) would match correctly but return "error: 1" instead of "Error: 1".
    • Lowercasing only one side. Calling line.contains(lowerPattern) fails for ["Error: 1"] because "Error: 1" does not contain "err" in that exact case. Both sides must be converted.
    • Lowercasing the pattern inside the loop. The result is correct, but the same conversion is repeated for every line.

    Testing

    • ["Error: 1", "ok"] with "ERR" gives "Error: 1".
    • ["Error: 1", "eRRor 2", "fine"] with "err" gives "Error: 1\neRRor 2".
    • ["abc"] with "xyz" gives "".
    • ["Hello World", "HELLO"] with "o w" gives "Hello World".
    • [] with "a" gives "".
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free