regex – What is the grep equivalent in Python?
You could use the
in keyword to check for your substring:
with open(text_file.txt, r) as f: for line in f.readlines(): if elephant in line: print(line)
Or, if you had a string
for line in s.split(n): if elephant in line: print(line)
Your regex only prints
elephant because thats what it captured: exactly your regex string. If you were to try the following regex instead:
test = re.search(r(.*?elephants.*?)n, I like elephants.nThey are nice)
Then youd have results for
test.group(1) which include the whole line before and after the elephants.
In : test.group(0) Out: I like elephants.n
Thats the whole captured string.
In : test.group(1) Out: I like elephants.
Thats just the capture group (string between parentheses).