Search code examples
pythonmultilinepython-re

How to find repeated pattern in multiline text with Python regex?


I am very new to Python's regex module. I am trying to find the problem number and corresponding company name which asked the question. My text looks like this:

Text input:

text = """
# Daily Coding Problem

Solutions to problems sent by dailycodingproblem.com

---

#### Problem 1

Given a list of numbers, return whether any two sums to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

Bonus: Can you do this in one pass?

[Solution](solutions/problem_001.py)

---

#### Problem 2

This problem was asked by Uber.

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Follow-up: what if you can't use division?

[Solution](solutions/problem_002.py)

---

#### Problem 3

This problem was asked by Google.

Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.

[Solution](solutions/problem_003.py)

---

"""

import re
from pathlib import Path

pat = r"Problem (\d+)$\n.*asked by (.*)\.$"
out = re.findall(pat,text,flags=re.MULTILINE)
print(out)

"""

My code attempt:

import re

pat = r"^Problem (\d+).* asked by (\w+[\s]\w+)."
out = re.findall(pat, text, flags=re.MULTILINE|re.DOTALL)

print(out)
# [('1', 'Google company')]

But I am getting the wrong output. How to get the correct expected answer:

problem_num = [2,3]
company = ["Uber", "Google"]

Solution

  • I assumed that the line with "asked by" is always after the problem number. For me it work with pattern.

    pat = r"### Problem (\d+)$\n*.*asked by ([a-zA-Z]+)\."
    out = re.findall(pat,text,flags=re.MULTILINE)
    

    $ - end of the line because of MULTILINE flag

    Note that this will get "Google company" not "Google"