Extracting text between three specific phrases using regex and findall() python

Viewed 39

I'm trying to extract text between three given phrases using the following regular expression

detail_re = r'(?=(\b(?:{0}|{1}|{2})(?:\s|no\.?|-|x)\b.*?\b(?:{3}|{4})\b.*?(?:{5})))'.format(token0, token1, token2, token3, token4, token5)
extracted_text_list = re.findall(detail_re, description,re.IGNORECASE)

There are three groups

  1. (?:{0}|{1}|{2})(?:\s|no.?|-|x)
  2. (?:{3}|{4})
  3. (?:{5})

These tokens are either strings or None.

If group 1 or 2 (or both) is None, then findall() returns None which is not the expected answer

e.g.

description: accommodation to form 2 No. three bedroom dwellings

  1. If token0, token1, token2, token3, token4 are None and token5 is dwellings, expected answer is 'dwellings'. However the it returns None
  2. If token0 is '2', token3, token4 are None and token5 is dwellings, expected answer is '2 No. three bedroom dwellings'. However the it returns None

I can correct this by setting groups optional with ?. But it results in incorrect outputs.

How can I correct this? Thanks in advance

0 Answers
Related