-1

i'm just a little confused about the combination of ^ with $. I understand

that it means start and end respectively and then () means extract specifically

what's inside the parenthesis. But why would it print no in this example. please

help with an explanation. thank you

if re.search('^(0|1)$', '0b'):
    print 'yes'
else:
    print 'no'
Square-root
  • 853
  • 1
  • 12
  • 25
  • 2
    The regex `^(0|1)$` will check if the string contains only a single character either `0` or `1`. – Tushar Mar 17 '16 at 03:07
  • thanks. i thought it looks for 0 or 1 from beginning to end. now i understand it sort of look for exactly 1 character length of either 0 or 1 – Square-root Mar 17 '16 at 03:21

1 Answers1

1

Your regular expression matches first the start of the string, then either character 0 or 1 followed by end of string. Since the string you're matching has b after 0 it won't match. Changing your regular expression to ^(0|1)b$ will produce a match.

niemmi
  • 17,113
  • 7
  • 35
  • 42