Finding multiple lines with a regex?
<p>I am trying to complete a "Regex search" project from the book <a href="https://automatetheboringstuff.com/chapter8/" rel="nofollow">Automate boring stuff with python</a>. I tried searching for answer, but I failed to find related thread in python.</p>

<p>The task is: "Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen."</p>

<p>With the below compile I manage to find the first match</p>

<pre><code>regex = re.compile(r".*(%s).*" % search_str)
</code></pre>

<p>And I can print it out with </p>

<pre><code>print(regex.search(content).group())
</code></pre>

<p>But if I try to use </p>

<pre><code>print(regex.findall(content))
</code></pre>

<p>The output is only the inputted word/words, not the whole line they are on. Why won't <code>findall</code> match the whole line, even though that is how I compiled the regex?</p>

<p>My code is as follows.</p>

<pre><code># Regex search - Find user given text from a .txt file
# and prints the line it is on

import re

# user input
print("\nThis program searches for lines with your string in them\n")
search_str = input("Please write the string you are searching for: \n")
print("")
# file input
file = open("/users/viliheikkila/documents/kooditreeni/input_file.txt")
content = file.read()
file.close()

# create regex
regex = re.compile(r".*(%s).*" % search_str)

# print out the lines with match
if regex.search(content) is None:
    print("No matches was found.")
else:
    print(regex.findall(content))
</code></pre>

<p>In python regex, parentheses define a <em>capturing group</em>. (See <a href="https://regex101.com/r/iV8nS1/1" rel="nofollow">here</a> for breakdown and explanation).</p>

<p><code>findall</code> will only return the captured group. If you want the entire line, you will have to iterate over the result of <code>finditer</code>.</p>

python regex python-3.x