0

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?

3
  • 1
    The pattern is rather fragile due to lots of subsequent optional patterns that may overlap. (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/1 Commented Jan 13, 2020 at 15:16
  • @WiktorStribiżew consignee must be present in the string to match. Thing is name and address of might be present before it (if present then match) or name and address might be present after it (if present then match). I can't make consignee optional or make name obligatory. Commented Jan 13, 2020 at 15:19
  • Try regex101.com/r/7pbqLa/3 Commented Jan 13, 2020 at 15:28

1 Answer 1

1

I removed some brackets in the pattern and it worked for me. Every part is optional besides consignee.

con = r"(consignee\s?(name)?\s?(and)?\s?(address)?|(name)?\s?(and)?\s?(address)?\s?(of)\s?consignee)"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.