0

new to regex here

I am trying to create a very basic pattern matching where user input has to be exactly 3 digits. In this example, for me it is invalid if I have less than 3. But any input with 3 or more digits is accepted. Shouldn't this be invalid if its greater than 3 digits?? Am I doing something wrong here?

import re


pattern = "[0-9]{3}"

user_input = input()
if(re.search(pattern, user_input)):
    print("valid")
else:
    print("invalid")
alex
  • 31
  • 4
  • 1
    This will match the `123` in `1234`. You might want `pattern = "^[0-9]{3}$"` – inspectorG4dget Nov 18 '22 at 15:41
  • ok this makes sense thank you! What if I needed to include a pattern that may or may not occur? my pattern may be "000" or it may be "000-0000". Is there a way to account for these possible characters? I apologize I just started regex yesterday so i am brand new – alex Nov 18 '22 at 15:52
  • Try `"^000(-0000)?$"` – inspectorG4dget Nov 18 '22 at 16:12

0 Answers0