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
- (?:{0}|{1}|{2})(?:\s|no.?|-|x)
- (?:{3}|{4})
- (?:{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
- If token0, token1, token2, token3, token4 are
Noneand token5 is dwellings, expected answer is 'dwellings'. However the it returnsNone - If token0 is '2', token3, token4 are
Noneand token5 is dwellings, expected answer is '2 No. three bedroom dwellings'. However the it returnsNone
I can correct this by setting groups optional with ?. But it results in incorrect outputs.
How can I correct this? Thanks in advance