1
votes

I want to match every week day in a string where all words are comma separated.

Examples: "mon, thu, fry" should be matched "mon, tue, sat" should be matched "" should not be matched "mon, tue, wed, thu, fri, sat, sun" should be matched "foo, bar" should not be matched

I came up with this regex but it matches only the string containing ALL week days:

^(mon|tue|wed|thu|fri|sat|sun)$

How can I match them "indipendently"?

I am using python3

2
What happens if a string has days mixed with non day words, e.g. mon, foo ?Tim Biegeleisen
Perhaps, ^(mon|tue|wed|thu|fri|sat|sun)(,\s*(mon|tue|wed|thu|fri|sat|sun))*$Wiktor Stribiżew
@TimBiegeleisen I should then handle that as an invalid string in my code. So the regex should not match anything... in an ideal worldrefex
@refex - Check anubhava's comment. It handles the scenario which Tim is describing as well.Utsav

2 Answers

1
votes

If you have the ability to use the newer regex module, you could use a recursive approach:

^((?:mon|tue|wed|thu|fri|sat|sun)(?:, )?)(?1)*$'


Python
import regex as re

string = """
mon, tue, fri
mon, tue, sat
mon, tue, wed, thu, fri, sat, sun
foo, bar
mon
tue
wed
mon, wed
"""

rx = re.compile(r'^((?:mon|tue|wed|thu|fri|sat|sun)(?:, )?)(?1)*$')
days = list(filter(lambda x: rx.match(x), string.split("\n")))
print(days)
0
votes

Rather than give you the direct answer, I'll try the teach you to fish approach.

Use an interactive regular expression facility (such as http://pythex.org), enter your tests strings first, then iterate on your regular expression string until all of the test strings match to your specification.

I'll give you a hint that you'll need to use a capture group and possibly a quantifier.

The interactive facility usually has a "regular expression cheatsheet" you can consult to give you ideas.

Good luck with your homework!