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
- Create an empty array of strings named
resultwithvar, for the matching lines. - Build the regex in a
letnamedregex. Put\bbefore and after the escaped pattern. Inside a Swift string literal each backslash is written twice, so the boundary is"\\b". The initializerNSRegularExpression(pattern:)can fail, so it is written withtry!, which stops the program if the regex is invalid. That can't happen here, because the escaped pattern is always valid. - Loop over the lines with
for line in lines, writing the closing brace right away. - Ask the regex for a match.
regex.firstMatch(in:options:range:)returns the first match, ornilif there is none, so compare the result withnil. Therangesays where to search, andNSRange(line.startIndex..., in: line)covers the whole line. - Keep the line by appending it to
result. One whole-word match anywhere in the line is enough. - 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.
NSRegularExpressionis not in the standard library, and it works in terms ofNSRange, a start and a length in UTF-16 units, not Swift'sString.Index. The initializerNSRange(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
\bare a backslash and a letter. In a Swift literal"\\b"is that two-character string, and"\\b".countis 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")isa\.b, so the dot matches only a dot. Without it,a.bwould also matchaXb. - The result is optional.
firstMatchreturns anNSTextCheckingResult?. Comparing it withnilasks 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\bnext to a non-word character requires a word character on the other side.
Testing
| lines | pattern | Result |
|---|---|---|
["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)" |
