Start learning free

LESSON 15 OF 71 · PROJECTS: COMMAND-LINE TOOLS

grep -v in Swift: Inverting a 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:

func grepInvert(_ lines: [String], _ pattern: String) -> String

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 the lines where !line.contains(pattern) is true, then return result.joined(separator: "\n").

The full solution:
class Solution {
    func grepInvert(_ lines: [String], _ pattern: String) -> String {
        var result = [String]()
        for line in lines {
            if !line.contains(pattern) {
                result.append(line)
            }
        }
        return result.joined(separator: "\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Grep V3 in Swift, explained

    Problem overview

    The third version of the grep project adds the -v flag. The function grepInvert(_ lines: [String], _ pattern: String) -> String 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.

    With pattern = "err" and lines = ["error", "ok", "another error", "fine"], the lines "error" and "another error" contain err and are dropped. The survivors are "ok" and "fine", so the result is "ok\nfine".

    Approach

    This is version 1 with the test flipped. There, a line was kept when line.contains(pattern) was true. Here a line is kept when that same check is false. Everything else, the empty array, the loop, the append and the final join, stays as it was.

    The flip is a single character. The logical-not operator ! placed in front of an expression turns true into false and the other way round, so !line.contains(pattern) reads as "the line does not contain the pattern".

    Step by step

    1. Create an empty array of strings named result with var. It will hold the lines that are kept.
    2. Loop over the lines with for line in lines, and write the closing brace right away.
    3. Test with a negation. Inside the loop, start an if on !line.contains(pattern). The ! goes in front of the whole call.
    4. Keep the line. Inside the if, append line to result. Only a line without the pattern gets here.
    5. Join and return with result.joined(separator: "\n"). When every line contained the pattern nothing was kept, and the join of an empty array is "".

    The solution in Swift

        func grepInvert(_ lines: [String], _ pattern: String) -> String {
            var result = [String]()
            for line in lines {
                if !line.contains(pattern) {
                    result.append(line)
                }
            }
            return result.joined(separator: "\n")
        }
    

    The details a learner might trip on:

    • Where the ! goes. It applies to the expression to its right. !line.contains(pattern) negates the result of contains. Swift has no not keyword, so ! is the only form.
    • Not the same as !=. != compares two values for difference. It would be the wrong tool here, since the question is about containing a substring, not being equal to the pattern.
    • Order is preserved. The loop visits the lines in order and append adds at the end, so the surviving lines keep their relative order with no extra work.

    Complexity

    The time is the same as for version 1: every line is searched for the pattern once, so the work grows with the total number of characters (times the pattern length in the worst case). Extra space is the array of kept lines and the joined string.

    Edge cases and common mistakes

    • Everything matches. ["error", "err"] with "err" returns "".
    • Nothing matches. Every line is kept, so ["a", "b"] with the pattern "zzz" returns "a\nb".
    • Case matters. With "err", the line "Err" doesn't contain the pattern as written, so it is kept: ["Err", "ok"] returns "Err\nok".
    • Empty array. The loop doesn't run and the result is "".
    • Forgetting the !. That gives version 1's behaviour, returning the matching lines instead of the others.
    • An empty pattern. It isn't defined by the statement. With Foundation imported, "abc".contains("") is false, so every line is kept.

    Testing

    linespatternResult
    ["error", "ok", "another error", "fine"]"err""ok\nfine"
    ["error", "err"]"err"""
    ["Err", "ok"]"err""Err\nok"
    []"e"""
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free