0

For example, my input for variable day can be Monday or Monday, Tuesday or Monday,..,Friday and I'm trying to use regex in python to just provide a pattern and check its input.

result = re.compile(r'\([S|M|T|W|Th|F|Sa]\)|\([S|M|T|W|Th|F|Sa],[S|M|T|W|Th|F|Sa]+\)')
day = "(T,Th)"
if result.match(day):
  print "matched"
else:
  print 'not'

What if the given input is (T,Th,F) or (T,Th,F,Sa)? What should I do to my pattern to handle these kind of input? Is there any solution so it wont be lengthy?

1
  • 2
    [] represents a character class, | is not an or operation there. Use (S|M|T|W|Th|F|Sa)... Commented Jan 24, 2014 at 16:11

2 Answers 2

4

An answer without regex would be:

week = ["S", "M", "T", "W", "Th", "F", "Sa"]
days = "(T,Th,C)"
no_match = False
for day in days[1:-1].split(","): #split separates your days-string, [1:-1] removes brackets
    if day not in week:
        no_match = True
        break
if no_match:
    print "not"
else:
    print "matched"

the [1:-1] are slicing notation, bascially it creates a string starting at character with index 1 (= 2nd character) and ending at the next-to-last character. In fact it removes the brackets.

Sign up to request clarification or add additional context in comments.

1 Comment

@user3226156 Basically excluding the first and last character. In his example, only includes T,Th,C.
3

Use this regex:

\((S|M|T|W|Th|F|Sa)(,\s*(S|M|T|W|Th|F|Sa))*\)

The (S|M|T|W|Th|F|Sa) matches any weekday. Be careful to use round parentheses, not square brackets, as these represent character classes (see Ashwini Chaudhary's comment)

This will match, for example:

  • (M, T, W)
  • (M)
  • (T, Sa, Fr)
  • (T,M,Th)

2 Comments

I see, that's what '*' is used for.
@user3226156 Yes, exactly. It means 'zero or more of this'.

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.