2

I have a program that expects an input saying "yes", something like:

my_input = raw_input('> ')
if my_input == 'yes':
    #etc

But that's too specific, I want the input to match this regex: [yY](es)?, so that if the user puts "yes, Yes, y or Y", it is the same. But I don't know how is this implemented in python.

I want something like:

regex = some.regex.method('[yY](es)?')
my_input = raw_input('> ')
if my_input == regex:
    #etc  

Thank you in advance.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
user2166141
  • 25
  • 1
  • 5

1 Answers1

7

Regex is probably overkill here, but here is one way to do it:

import re
regex = re.compile(r'y(es)?$', flags=re.IGNORECASE)
my_input = raw_input('> ')
if regex.match(my_input):
    #etc 

This will match the strings "y" or "yes" with any case, but will fail for a string like "yellow" or "yesterday".

Or better yet, the same behavior without regex:

my_input = raw_input('> ')
if my_input.lower() in ('y', 'yes'):
    #etc

Note: in Python 3 raw_input has been replaced by input.

Niels Abildgaard
  • 2,662
  • 3
  • 24
  • 32
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306