Regex to pick up text between markers and includes last mark

Viewed 62

looking for a quick solution to pick up the text following a numeric value that looks like this:

text to extract

4.71. Firms should determine the frequency and intensity of monitoring on a risk-sensitive basis, 
taking into account the nature, size and complexity of their business and the level of risk to which they are exposed.   

4.72.  text 
4.9. text
4.9 addf
4.73.  text
4.74.  text 

Solution

(?<=\d\.\d\d\.) [\w+\W*]*?(?=\r?\d\.\d\.*)

I would also need to include the last text after 4.74 which currently does not work.

UPDATE to extract text after alphabetical enumeration

Question: How can I amend the logic to work to capture the text after these enumerations?

a) text 
text

a. text text

ii. text

iv. text
iii. text text 
2 Answers

We can use re.findall here as follows:

inp = """4.71. Firms should determine the frequency and intensity of monitoring on a risk-sensitive basis, taking into account the nature, size and complexity of their business and the level of risk to which they are exposed.

4.72. text 4.9. text 4.9 addf 4.73. text 4.74. text"""

matches = re.findall(r'\b\d+(?:\.\d+)?\.? (.*?)\s*(?=\b\d+(?:\.\d+)?|$)', inp, flags=re.DOTALL)
print(matches)

This prints:

['Firms should determine the frequency and intensity of monitoring on a risk-sensitive basis, taking into account the nature, size and complexity of their business and the level of risk to which they are exposed.',
 'text', 'text', 'addf', 'text', 'text']

The idea is to find every numerical header, then capture only the content following it. We capture all content up until either hitting the next header, or reaching the end of the file.

If the numbers are at the start of the string, you can match the number followed capturing by all lines that do not start with a digit and a number.

Note that it does not match 4.9 addf as there is no ending .

^\d+(?:\.\d+)+\. (.*(?:\r?\n(?!\d+\.).*)*)
  • ^ Start of string
  • \d+(?:\.\d+)+ Match 1+ digits, repeat a . and 1+ digits and match the ending .
  • \. Match .
  • ( Capture group 1
    • .* Match the rest of the line
    • (?: Non capture group
      • \r?\n(?!\d+\.).* Match a newline, the rest of line not starting with digits and .
    • )* Close group and optionally repeat
  • ) close group

Regex demo | Python demo

Related