Python wildcard

I have a python script that accepts input using a pattern like this: 1 ** then accepts several inputs after that, e.g. 100, 110, 011, etc. I need to check if the imputed data matches the pattern * can mean either 1 or 0. What is the best way to do this? I am new to Python, so the explanations will be helpful.

Update : added sample input and output

Example of correct input and output:

input: ** 1 (sample) 001, 101, 000 output: 001, 101

+4
source share
3 answers

I would suggest using the input string and replace to create a simple regular expression:

 >>> '1**0*'.replace('*', '[01]') '1[01][01]0[01]' 

Now it can be used in any way:

 >>> import re >>> pattern = '1**0*'.replace('*', '[01]') >>> bool(re.match(pattern, '00000')) False >>> bool(re.match(pattern, '10000')) True 

If you are not familiar with regular expressions, you may need to read a textbook or two. But the main idea is that any of the characters between the brackets is allowed. Thus, [01] matches either 1 or 0, as you asked in your question.

+3
source

I would use zip instead of regular expressions. It aligns all elements of both lines and allows you to scroll 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 to do this with @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)) 
+1
source

regex may match your input:

 import re yourinput = "100"; matchObj = re.match( r'(1..', yourinput) 

the dot is probably what you described with your star.

there are many tutorials that, for example, describe what you can do with matchobject, see http://www.tutorialspoint.com/python/python_reg_expressions.htm for a tutorial or here for documentation of the library http://docs.python.org/ library / re.html

0
source

Source: https://habr.com/ru/post/1394885/


All Articles