I've this regex :
con = r"(((consignee)\s?(name)?\s?(and)?\s?(address)?)|((name)?\s?(and)?\s?(address)?\s?(of)?\s?(consignee)))"
I'm trying to match with the following texts :
txt1 = 'NAME AND ADDRESS OF CONSIGNEE :'
txt2 = ' consignee name and address :'
I'm using re.finditer() like this :
match1 = [i.group() for i in re.finditer(con, txt1, re.IGNORECASE)]
match2 = [i.group() for i in re.finditer(con, txt2, re.IGNORECASE)]
The result I'm getting is this :
>>> match1
['NAME AND ADDRESS OF CONSIGNEE']
>>> match2
[' consignee']
My desired output is ['consignee name and address'] for match2. Even though I've already added this into regex, why is it not capturing the group?
I've tried re-ordering the regex like this :
con = r"(((name)?\s?(and)?\s?(address)?\s?(of)?\s?(consignee))|((consignee)\s?(name)?\s?(and)?\s?(address)?))"
But still in this case also, match2 is always only [' consignee']. I've also checked out regex101 here, which is also giving the same result. What am I doing wrong?
(name)?is optional, but(consignee)is not. Make(consignee)optional, or make both obligatory (remove?after(name)). Probably, the latter is better, see regex101.com/r/aelbVu/1consigneemust be present in the string to match. Thing isname and address ofmight be present before it (if present then match) orname and addressmight be present after it (if present then match). I can't makeconsigneeoptional or makenameobligatory.