Reputation: 706
So im trying to have my script check to make sure the user input is in a correct format. for example, I'm trying to get the user to input a string that looks like:
0B/4B/07
I want to make sure the script knows that the string should look exactly like that with varying numbers and letters, but is a total len of 8 characters, and the /'s are in exactly those positions. I know there should be a way to do this with the re module but i cant seem to figure it out. Any suggestions?
Upvotes: 1
Views: 176
Reputation: 1394
The following will test that the users input matches your format with re.search
and then use re.findall
to assign a tuple with each of the matches to the variable matches
. [A-Za-z0-9]
matches any alphanumeric character, while {2}
indicates that there should be two matches of the prior character. In addition, wraping characters in ()
indicates that you want to return them in an re.findall
.
import re
text = "0B/4B/07"
def get_input(text):
if re.search("[A-Za-z0-9]{2}/[A-Za-z0-9]{2}/[A-Za-z0-9]{2}", text):
matches = re.findall(
"([A-Za-z0-9]{2})/([A-Za-z0-9]{2})/([A-Za-z0-9]{2})",
text
)[0]
return matches
else:
return None
Usage:
>>> text = "0B/4B/07"
>>> get_input(text)
('0B', '4B', '07')
Upvotes: 0
Reputation: 8154
import re
def check(word):
pattern = "^[0-9A-Z]{2,2}/[0-9A-Z]{2,2}/[0-9A-Z]{2,2}$"
m = re.search(pattern,word)
if m:
print("true")
else :
print("false")
#############################
> check('0B/4B/07') o/p true
>check('0B/4B/075') o/p false
You can use regex for this
Or if len(x) == 8 and x[2] == '//' and x[5] == '//'
some thing like this as suggested by @Tim Castelijns
Upvotes: 1