Okay, here is a regex to match a block with that structure, considering it can span multiple lines.
^\d+([\s\S]*?)\d+\s\|\s\d+$
This regex requires the multiline flag (m) to be enabled for ^ and $ to match the start and end of lines within the string, not just the start and end of the entire string.
Let's break it down:
^: Asserts the position at the start of a line (due to the multiline flag). This ensures the block starts with a number at the beginning of a line.
\d+: Matches one or more digits (the starting number).
([\s\S]*?): This is the core part that matches the content between the start and end numbers.
[\s\S]: Matches any whitespace character (\s) OR any non-whitespace character (\S). This effectively matches any character, including newlines.
*: Matches the previous character class ([\s\S]) zero or more times.
?: Makes the * quantifier non-greedy. This is crucial! It means it will match the shortest possible string that allows the rest of the regex to match. Without this, [\s\S]* would greedily match everything until the last number | number pattern in the entire file, not just the one ending the current block.
(...): Creates a capturing group around the middle content. You can remove the parentheses if you don't need to specifically extract only the middle part.
\d+: Matches one or more digits (the first number in the final pattern).
\s: Matches a whitespace character (the space before the pipe).
\|: Matches the literal pipe character (|). It's escaped because | is a special regex character.
\s: Matches a whitespace character (the space after the pipe).
\d+: Matches one or more digits (the second number in the final pattern).
$: Asserts the position at the end of a line (due to the multiline flag). This ensures the number | number pattern is at the end of a line.
How to use it (Example in Python):
import re
text = """
9 para prp to, for, in order to
• as informações são comprimidas para serem
transmitidas – The information is com-
pressed to be sent.
100 | 204357
10 next block starts here
some content
over multiple
lines
20 | 30
11 another one
ending here
40 | 50
"""
# The regex pattern with the multiline flag enabled (re.M)
regex = r"^\d+[\s\S]*?\d+\s\|\s\d+$"
# Find all matches
matches = re.findall(regex, text, re.M)
# Print the found blocks
for match in matches:
print("-" * 20) # Separator for clarity
# findall with a capturing group usually returns just the captured group
# If you remove the capturing group (([\s\S]*?)), findall will return the whole match
# Let's use finditer to get the whole match object
for match in re.finditer(regex, text, re.M):
print("-" * 20)
print(match.group(0)) # group(0) is the entire match
This will correctly identify and extract each block based on the specified start and end patterns on their respective lines.