regex – What is the grep equivalent in Python?

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 s with n characters:

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(0) and test.group(1) which include the whole line before and after the elephants.

In [22]: test.group(0)
Out[22]: I like elephants.n

Thats the whole captured string.

In [23]: test.group(1)
Out[23]: I like elephants.

Thats just the capture group (string between parentheses).

regex – What is the grep equivalent in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *