Start learning free

LESSON 15 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -v in Java: Inverting the Match with !contains

Practice Read the full explanation

Build the -v flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that DO NOT contain pattern as a substring (case-sensitive). Return the remaining lines (the ones that do not contain the pattern), in their original order, joined by newline characters (\n).

Function signature:

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

Example:

Input:
pattern = "err"
lines = ["error", "ok", "another error", "fine"]

Output: "ok\nfine"

When printed:
ok
fine

If every line contains the pattern, return the empty string "".


Same as grep v1 but flip the condition: keep lines where !line.contains(pattern).

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

STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Grep V3 in Java, explained

    Problem overview

    The method grepInvert takes a List<String> named lines and a search string pattern. It returns the lines that do not contain the pattern as a substring, in their original order, joined by newline characters. The match is case-sensitive. If every line contains the pattern, the result is the empty string "".

    For pattern = "err" and lines = ["error", "ok", "another error", "fine"] the result is "ok\nfine". Printed, that is:

    ok
    fine
    

    This is the -v flag of Unix grep: the same test as the plain substring search, with the answer reversed.

    Approach: keep the lines where the test is false

    The previous version kept a line when line.contains(pattern) was true. Here the structure of the method stays the same and only the condition flips: keep a line when that call is false. In Java, putting ! in front of a boolean expression negates it, so the whole change is one character in the if.

    Everything else carries over. A list collects the lines to keep because their number is unknown in advance, a for-each loop visits the lines in order so the order is preserved, and String.join turns the list into a single string with newlines between the elements.

    Step by step

    1. Create result, an empty ArrayList held in a List<String> variable, for the lines to keep.
    2. Loop over the lines with a for-each loop that names each entry line.
    3. Test for absence with if (!line.contains(pattern)). The ! applies to the whole contains call, so the condition is true exactly when the pattern is nowhere in the line.
    4. Keep the line with result.add(line). Only a line without the pattern reaches this statement.
    5. Join and return with String.join("\n", result). If every line contained the pattern, nothing was added, and joining an empty list gives "", which is the required answer.

    The solution in Java

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

    The Java details worth a closer look:

    • The scope of !. !line.contains(pattern) reads as "not (line contains pattern)". The method call happens first, and the ! flips its boolean result. There is no need for extra parentheses here.
    • The same literal search. contains compares plain characters and is case-sensitive. With ["Error", "error"] and the pattern "error", the line "Error" does not contain it, so the result is "Error".
    • Original order. Lines are appended as the loop reaches them, so the kept lines appear in the order they had in the input.
    • 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: every line is scanned once by contains, and the join copies the kept characters once. For short patterns this is close to O(m).

    Space: O(n + m). The list holds up to n references and the joined string holds up to about m characters.

    Edge cases and common mistakes

    • Every line matches. ["error", "another error"] with "err" gives "".
    • An empty list. With no lines, nothing is kept and the result is "".
    • An empty pattern. Every string contains "", so every line is rejected: ["a", "b"] with "" gives "".
    • Empty lines are kept. An empty line does not contain a non-empty pattern, so it survives. ["a", "", "b"] with "z" gives "a\n\nb", with a blank line in the middle.
    • Nothing to remove. ["a", "b"] with "z" returns "a\nb", all lines.
    • Forgetting the !. The method then behaves like the plain search and returns the opposite set of lines.
    • Removing from the list while looping. A tempting alternative is to call lines.remove inside the loop. That changes the caller's list, and removing from an ArrayList during a for-each loop usually ends in a ConcurrentModificationException. Building a separate result list avoids both problems.

    Testing

    • ["error", "ok", "another error", "fine"] with "err" gives "ok\nfine".
    • ["error", "another error"] with "err" gives "".
    • ["Error", "error"] with "error" gives "Error".
    • ["a", "", "b"] with "z" gives "a\n\nb".
    • ["a", "b"] with "" 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