Home > Enterprise >  How to print else only IF f1 is a match
How to print else only IF f1 is a match

Time:04-20

The below RegEx is currently working fine. It will return IF f1 and either f2 or f3 have a match.

I need help figuring out how to print else only IF f1 is a match e.g. print("What city and what month?)

import re

string = ['I am looking to rent a home in Los Angeles']

for s in string:
    f1 = re.findall(r'(.{0,50}\b(home|house|condo)\b.{0,50})',s, re.IGNORECASE)
    if f1:

        f2 = re.findall(r'(.{0,50}\b(los angeles|la)\b.{0,50})',f1[0][0], re.IGNORECASE)
        if f2:
            print("For what month?")

        f3 = re.findall(r'(.{0,50}\b(june|july|august)\b.{0,50})',f1[0][0], re.IGNORECASE)
        if f3:
            print("For what city?")```

CodePudding user response:

After you are sure f1 matches, collect f2 and f3 matches. Then check if f2 or f3 matched, otherwise, do f1 block:

import re
 
string = ['I am looking to rent a home in Los Angeles']
 
for s in string:
    f1 = re.search(r'.{0,50}\b(home|house|condo)\b.{0,50}',s, re.IGNORECASE)
    if f1:
        f2 = re.findall(r'(.{0,50}\b(los angeles|la)\b.{0,50})', f1.group(), re.IGNORECASE)
        f3 = re.findall(r'(.{0,50}\b(june|july|august)\b.{0,50})', f1.group(), re.IGNORECASE)
        if f2:
            print("For what month?")
        elif f3:
            print("For what city?")
        else:
            print("Only f1 fired, not f2 and f3")
    else:
        print("No f1!")
  • Related