Start learning free

LESSON 16 OF 71 · PROJECTS: COMMAND-LINE TOOLS

grep -w in Swift: Whole-Word Match with NSRegularExpression

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:

func grepWord(_ lines: [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 NSRegularExpression from Foundation with \b word-boundary anchors. Wrap the pattern itself with NSRegularExpression.escapedPattern(for:) to escape any regex metacharacters.

let regex = try! NSRegularExpression(
    pattern: "\\b" + NSRegularExpression.escapedPattern(for: pattern) + "\\b"
)
// per line: if regex.firstMatch(in: line, options: [], range: ...) != nil keep


The full solution:
class Solution {
    func grepWord(_ lines: [String], _ pattern: String) -> String {
        var result: [String] = []
        let regex = try! NSRegularExpression(pattern: "\\b" + NSRegularExpression.escapedPattern(for: pattern) + "\\b")
        for line in lines {
            if regex.firstMatch(in: line, options: [], range: NSRange(line.startIndex..., in: line)) != nil {
                result.append(line)
            }
        }
        return result.joined(separator: "\n")
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in Swift, explained

    Problem overview

    The fourth version of the grep project adds the -w flag. The function grepWord(_ lines: [String], _ pattern: String) -> String returns the lines that contain the pattern as a whole word: the character just before the match and the character just after it must not be word characters, meaning letters, digits or underscores. The pattern is a single word, the match is case-sensitive, and the kept lines are joined by newline characters. No match gives the empty string.

    With pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". "concat" is rejected because cat is preceded by the word character n, and "category" is rejected because it is followed by e. A line may contain the pattern more than once, and one whole-word occurrence is enough: "concat cat" is kept because of its second cat.

    Approach

    A plain contains can't tell cat in the cat from cat in concat. Checking the neighbours of every occurrence by hand is possible but fiddly, because a line can hold several occurrences and each one needs its own check at both ends.

    A regular expression expresses the rule directly. In a regex, \b is a word boundary: a position between a word character and a non-word character, or between a word character and the edge of the line. The regex \bcat\b therefore matches cat only when both of its sides are boundaries. Since the regex search tries every position in the line, the second cat in "concat cat" is found with no extra code.

    The pattern comes from the caller, so it should be treated as plain text and not as regex syntax. NSRegularExpression.escapedPattern(for:) does that by adding backslashes in front of special characters. Build the regex once, before the loop, and reuse it for every line.

    Step by step

    1. Create an empty array of strings named result with var, for the matching lines.
    2. Build the regex in a let named regex. Put \b before and after the escaped pattern. Inside a Swift string literal each backslash is written twice, so the boundary is "\\b". The initializer NSRegularExpression(pattern:) can fail, so it is written with try!, which stops the program if the regex is invalid. That can't happen here, because the escaped pattern is always valid.
    3. Loop over the lines with for line in lines, writing the closing brace right away.
    4. Ask the regex for a match. regex.firstMatch(in:options:range:) returns the first match, or nil if there is none, so compare the result with nil. The range says where to search, and NSRange(line.startIndex..., in: line) covers the whole line.
    5. Keep the line by appending it to result. One whole-word match anywhere in the line is enough.
    6. Join and return with result.joined(separator: "\n").

    The solution in Swift

    class Solution {
        func grepWord(_ lines: [String], _ pattern: String) -> String {
            var result: [String] = []
            let regex = try! NSRegularExpression(pattern: "\\b" + NSRegularExpression.escapedPattern(for: pattern) + "\\b")
            for line in lines {
                if regex.firstMatch(in: line, options: [], range: NSRange(line.startIndex..., in: line)) != nil {
                    result.append(line)
                }
            }
            return result.joined(separator: "\n")
        }
    }
    

    The details a learner might trip on:

    • Foundation provides the regex class. NSRegularExpression is not in the standard library, and it works in terms of NSRange, a start and a length in UTF-16 units, not Swift's String.Index. The initializer NSRange(line.startIndex..., in: line) converts the whole line's range. For "cat sat" it gives location 0 and length 7.
    • Doubled backslashes. The two characters of \b are a backslash and a letter. In a Swift literal "\\b" is that two-character string, and "\\b".count is 2. A single "\b" is not a valid escape in Swift and won't compile.
    • try! turns a thrown error into a crash. It is acceptable here only because the pattern is always escaped first, and unsafe in general for patterns that come from users unescaped.
    • Escaping matters. escapedPattern(for: "a.b") is a\.b, so the dot matches only a dot. Without it, a.b would also match aXb.
    • The result is optional. firstMatch returns an NSTextCheckingResult?. Comparing it with nil asks only whether a match exists, and the match's details aren't needed.

    Complexity

    The regex is compiled once. Each line is then scanned in time proportional to its length, so the total time is proportional to the number of characters in all lines. Extra space is the kept lines and the joined result, plus the compiled regex.

    Edge cases and common mistakes

    • Underscores and digits are word characters. With the pattern "cat", the lines "cat_x", "x_cat" and "cat1" are all rejected.
    • Other punctuation ends a word. "cat-s", "cat!" and "(cat)" all count as whole-word matches.
    • Case matters. "Cat" doesn't match "cat".
    • Several occurrences. A line is kept if any occurrence is a whole word, so "concat cat" is kept.
    • Leaving out escapedPattern. Characters like . in the pattern would act as regex syntax and match more than they should.
    • Patterns that don't start and end with word characters. The statement limits the pattern to letters, digits and underscores. A pattern like "+" finds nothing in "a+ b" or in "+", because \b next to a non-word character requires a word character on the other side.

    Testing

    linespatternResult
    ["cat sat", "concat", "the cat", "category"]"cat""cat sat\nthe cat"
    ["concat cat", "cat_x", "x_cat", "cat1", "cat-s", "Cat", "cat"]"cat""concat cat\ncat-s\ncat"
    ["a.b is here", "aXb", "xa.b"]"a.b""a.b is here"
    ["cat!", "(cat)", ""]"cat""cat!\n(cat)"
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free