grep: Filter Matching Lines
Medium
+3 pts
Unix tools
4/6
🎯 grep keeps the lines that match a pattern. Real grep also has flags: -i (ignore case) and -v (invert = keep the non-matches).
In Python:
def grep(
text: str, pattern: str, ignore_case: bool = False, invert: bool = False
) -> Generator[str, None, None]:
lines = text.splitlines()
if ignore_case:
pattern = pattern.lower()
for line in lines:
hay = line.lower() if ignore_case else line
found = pattern in hay
keep = not found if invert else found
if keep:
yield line
# or xor logic
# if (pattern in hay) != invert:
# yield line
Substring test and case folding
line.contains(pattern) is Rust's pattern in line. For case-insensitive matching, you can use .to_lowercase().
A note on the signature - what is 'a ?
fn grep<'a>(text: &'a str, pattern: &str, ignore_case: bool, invert: bool) -> Vec<&'a str>
In Python, the returned list owns its strings, and the garbage collector (GC) keeps text alive as long …
Login to see the full exercise.
Topics