I have a string which contains two shifts opening and closing time for each days of a week separated by hyphen (-). The day of week start with Monday going upto Sunday.
For example a weekly shift value is like '08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-16:00-00:00-00:00-00:00-00:00'.
There is two shift in a day so Monday to Friday shifts opening hours would be like 08:00-11:00-13:00-19:00 and that for Saturday would be 08:00-11:00-13:00-16:00 and for Sunday would be 00:00-00:00-00:00-00:00. From this I want to find opening and closing hours for each day using regex.
For example:
Monday - 08:00-19:00
Tuesday - 08:00-19:00
Wednesday - 08:00-19:00
Thursday - 08:00-19:00
Friday - 08:00-19:00
Saturday - 08:00-16:00
Sunday - 00:00-00:00
May I know how this can be achieved using regex in Python using re.split()? I am new to it.
CodePudding user response:
I don't see why you want to use regex. you can just split the string on hyphen (-) and then you will get a list of times. Then group them each day will be 4 items and in each group you will have the first two items making the first shift and the last two items making the last shift.
shifts = '08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08...'
shifts_lst = shifts.split("-")
days = []
weekDays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
for i in range(0,len(shifts_lst), 4):
days.append(shifts_lst[i:i 4])
for i, day in enumerate(weekDays):
print(day,"first shift" ,days[i][:2])
print(day,"second shift" ,days[i][2:])
CodePudding user response:
For this case you don't need regex, we can simply use,
st='08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-16:00-00:00-00:00-00:00-00:00'
res=st.split('-')
days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
for i in range(0,len(res),4):
print("{} - {}-{}".format(days[i//4],res[i],res[i 3]))
Hope this helps.
CodePudding user response:
If you want to use regex we can use re.findall()
import re
hours = '08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-19:00-08:00-11:00-13:00-16:00-00:00-00:00-00:00-00:00'
res = re.findall(r'([^-] )',hours)
weekdays=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
result=""
for i in range(0,7):
result = weekdays[i] '-' res[4*i] '-' res[4*i 3] '\n'
print(result)
output
Monday-08:00-19:00
Tuesday-08:00-19:00
Wednesday-08:00-19:00
Thursday-08:00-19:00
Friday-08:00-19:00
Saturday-08:00-16:00
Sunday-00:00-00:00