Search code examples
pythonregexsearchbuilt-infindall

How to write a regex in python to recognize days inside a string


In this assignment, the input wanted is in this format:

Regular: 16Mar2009(mon), 17Mar2009(tues), 18Mar2009(wed) ...

Reward: 26Mar2009(thur), 27Mar2009(fri), 28Mar2009(sat)

Regular or Reward is the name of customer type. I separated this string like this.

entry_list = input.split(":") #input is a variable  
client = entry_list[0] # only Regular or Reward  
dates = entry_list[1] # only dates  
days = dates.split(",")       

But now I need to count weekdays or weekend days inside the days list:

days = [' 16Mar2009(mon)', ' 17Mar2009(tues)', ' 18Mar2009(wed)']    

When it is mon tues wed thur fri, all count as weekday, and I need to know how many weekdays the input have.

When it is sat sun must be counted as weekend days, and I need to know how many weekends the input have.

How to write a regex in python to search for all weekdays and weekend days inside this list and count them, putting the number of weekdays and weekend days in two different counters?

EDIT

I wrote this function to check if the dates are in the write format but it's not working:

def is_date_valid(date):
    date_regex = re.compile(r'(?:\d{1,2}[A-Za-z]{3}\d{4}\([A-Za-z]{3}\),\s+){2}\d{1,2}[A-Za-z]{3}\d{4}\([A-Za-z]{3}\)$')
    m = date_regex.search(date)

m is only returning None


Solution

  • You don't really need a regex for this. You can just look for "sat" and "sun" tags directly, since your days are formatted the same way (i.e. no capitals, no "tue" instead of "tues", etc.) you shouldn't need to generalize to a pattern. Just loop through the list and look for "sat" and "sun":

    import re #if you are using the re
    
    days = [' 16Mar2009(mon)', ' 17Mar2009(tues)', ' 18Mar2009(wed)', ' 18Mar2009(sat)', ' 18Mar2009(sun)']
    weekends = 0
    weekdays = 0
    
    for day in days:
      if "sat" in day or "sun" in day:  #if re.search( '(sat|sun)', day ): also works
        weekends = weekends+1
      else:
        weekdays = weekdays+1
    
    print(weekends)
    print(weekdays)
    
    >>>2
    >>>3
    

    if you need to use a regex, because this is part of an assignment for example, then this variation of the if statement will do it: if re.search( '(sat|sun)', day ): This isn't too much more useful than just using the strings since the strings are the regex in this case, but seeing how to put multiple patterns together into one regex with or style logic is useful so I'm still including it here.