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")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
