Reputation: 123
I have a python script that takes input using a pattern like this: 1** then takes multiple inputs after that like 100, 110, 011 ect. I need to test to see if the imputed data matches the pattern, the * can stand for either a 1 or a 0. What is the best way to go about doing this? I'm fairly new to Python, so explanations would be helpful.
Update: added input and output example
Example of correct input and output:
input: **1 (pattern) 001, 101, 000 output: 001, 101
Upvotes: 4
Views: 5541
Reputation: 86220
I'd use zip
instead of Regular Expressions. It lines up all of the elements of both strings and lets you loop through each pair.
def verify(pat, inp):
for n,h in zip(pat, inp):
if n == '*':
if h not in ('0', '1'):
return False
elif h not in ('0', '1'):
return False
elif n != h:
return False
return True
# Example use:
>>> verify('**1', '001')
True
>>> verify('**1', '101')
True
>>> verify('**1', '000')
False
A shorter way of doing it by @DSM.
def verify(n, h):
return all(c0 == c1 or (c0 == '*' and c1 in '01') for c0, c1 in zip(n, h))
# or even shorter
verify = lambda n,h: all(c0 == c1 or (c0 == '*' and c1 in '01') for c0, c1 in zip(n, h))
Upvotes: 1
Reputation: 150987
I would suggest using the input string and replace
to generate a simple regular expression:
>>> '1**0*'.replace('*', '[01]')
'1[01][01]0[01]'
Now that can be used in whatever way you want:
>>> import re
>>> pattern = '1**0*'.replace('*', '[01]')
>>> bool(re.match(pattern, '00000'))
False
>>> bool(re.match(pattern, '10000'))
True
If you aren't familiar with regular expressions, you might want to read a tutorial or two. But the fundamental idea is that any one of the characters between brackets is allowed. So a [01]
matches either a 1 or a 0, as you requested in your question.
Upvotes: 3
Reputation: 3671
regex can match the input you described:
import re
yourinput = "100";
matchObj = re.match( r'(1..', yourinput)
the dot is probably what you described with your star.
there are lots of tutorial, that e.g. describe what you can do with a matchobject, look here http://www.tutorialspoint.com/python/python_reg_expressions.htm for a tutorial or here for the library documentation http://docs.python.org/library/re.html
Upvotes: 0