HOWTO · Python
Python Regular Expression to Match a Multiline Block of Text
This tutorial demonstrates how to find and match multiple lines of text using regular expressions in Python.
On this page
To find a known line inside a multiline string, use re.search() with re.MULTILINE. To capture a variable block whose nonempty lines may be separated by blank lines, normalize CRLF to LF and match the first line plus each blank-line separator and following line. The examples below use actual newline characters in their strings.
Match a known line with re.MULTILINE
re.MULTILINE changes how the anchors ^ and $ work: they match at the start and end of each line, as well as at the string boundaries. It does not make . match newline characters. Use re.search() when you need the first occurrence of a known line:
Run this example:
import re
text = "Header\nRegular Expression\nFooter"
match = re.search(r"^Regular Expression$", text, re.MULTILINE)
print(match.group(0) if match else "No matching line")
The anchors keep the match to the whole line. Without re.MULTILINE, ^ matches only at the start of the string, while $ matches at the end of the string or immediately before a final newline. With re.MULTILINE, $ also matches immediately before each newline, so this pattern can match a line embedded before other content.
Match nonempty lines across blank lines
For content that can vary, use a character class that excludes line endings for each content line. Normalize Windows CRLF line endings first; this makes the separator explicit and avoids carrying a carriage return into the matched text. The pattern below matches one nonempty line, followed by zero or more groups consisting of a blank line and another nonempty line. A blank line may contain spaces or tabs. It stops at the next separator that is not followed by content.
import re
text = """First paragraph line
Second paragraph line
\t
Third paragraph line"""
normalized = text.replace("\r\n", "\n")
pattern = re.compile(r"^[^\n]+(?:\n[ \t]*\n[^\n]+)*", re.MULTILINE)
match = pattern.search(normalized)
print(match.group(0) if match else "No matching block")
This pattern treats each nonempty line as part of the same block only when blank lines separate it from the next line. It includes the blank-line separators in the match. If your input uses lone carriage returns (\r) as line endings, normalize those separately; the CRLF replacement handles only \r\n. If whitespace-only lines should count as content instead of blank lines, adjust the separator rule to fit that input.
Choose an API for one or many matches
Use re.search() when the first matching block is enough; it returns a Match object or None. Use re.finditer() to process every non-overlapping match; it returns an iterator of Match objects, which also provide match positions. Use re.findall() when you want a list of matched strings; capturing groups change its result to captured strings or tuples, so a non-capturing group such as (?:...) is useful when only the whole match is needed.
re.compile() returns a reusable pattern object. It is convenient when a pattern or its flags are reused, as in the preceding example, but compiling is not required for a single call: the module functions accept a pattern string directly. The exact protected names are re.search(), re.finditer(), re.findall(), and re.compile(); re.MULTILINE is a flag, not a method.
Understand and test the pattern
In the variable-block pattern, [^\n]+ consumes one or more characters other than LF, so it cannot cross a line boundary. \n[ \t]*\n matches a line break, an optional whitespace-only line, and the next line break. The outer (?:...)* repetition allows additional blank-line-separated content lines without capturing each repetition; with no separating space, * quantifies the group immediately before it. The ^ anchor, paired with re.MULTILINE, lets the search begin at any line; it does not change how the content character class behaves.
Run this example:
import re
pattern = re.compile(r"^[^\n]+(?:\n[ \t]*\n[^\n]+)*", re.MULTILINE)
lf_text = "First line\n\nSecond line"
crlf_text = "First line\r\n\r\nSecond line"
no_match_text = "\n\n"
for label, text in (("LF", lf_text), ("CRLF", crlf_text)):
normalized = text.replace("\r\n", "\n")
match = pattern.search(normalized)
print(f"{label}: {match.group(0)!r}" if match else f"{label}: No match")
no_match = pattern.search(no_match_text)
print(f"No-match input returns None: {no_match is None}")
LF: 'First line\n\nSecond line'
CRLF: 'First line\n\nSecond line'
No-match input returns None: True
Test the pattern against the line endings and blank-line conventions in your source data. This runnable check supplies LF and CRLF strings separately, normalizes CRLF before matching, and also checks input with no nonempty line. The pattern handles LF and CRLF this way but does not normalize lone CR. A no-match result is None, so check it before accessing group(). If you need every block rather than the first one, use finditer() with the same compiled pattern. Because matching stops when the next blank separator is not followed by a nonempty line, consecutive paragraphs separated by blank lines are treated as separate blocks.