Python 3.3 Regular Expressions?

时间:2016-04-25 09:10:25

标签: python regex python-3.x verification

I've been studying Python for GCSE but can't get my code to work like it should (It will accept 4 digit+ numbers even though it shouldn't) even though I've verified that the coding is fine through teachers etc.

import re
val = input("Please enter a three-digit number: ")
valid = re.match("[0-9]{3}",val)
if valid:
       print("Accepted. ")
else:
       print("Rejected. Invalid input. ")

I really don't know why this isn't working right. Anyone got any ideas??

1 个答案:

答案 0 :(得分:0)

re.match matches as long as the pattern matches at the beginning of the given string. You need to use $ to ensure the string also ends with the string:

valid = re.match("[0-9]{3}$",val)

>>> re.match('[0-9]{3}', '123')
<_sre.SRE_Match object at 0x7effd9905f38>
>>> re.match('[0-9]{3}', '1234')
<_sre.SRE_Match object at 0x7effd9852030>


>>> re.match('[0-9]{3}$', '123')
<_sre.SRE_Match object at 0x7effd9905f38>
>>> re.match('[0-9]{3}$', '1234')
>>>