Error while searching for pattern in input using Python 3
I am trying to figure out the number of patterns that have a shape 1[0]1
in an input number. Pattern: there can be any number of zeros between two 1s , as in 893 10001 898.
I wrote code to accomplish this in Python 3.5 using regular expression ( re ) that looks like this:
>>> import re
>>> input1 = 3787381001
>>> pattern = re.compile('[10*1]')
>>> pattern.search(input1)
But this is throwing me the following error :
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
pattern.match(input1)
TypeError: expected string or bytes-like object
Is there a workaround to clearly determine if the above pattern is present 1[0]1
in the input number?
source to share
The pattern [10*1]
matches a single char that is 1
, 0
or *
. In addition, the regex engine only searches for matches within text, it needs a string as an input argument.
Remove the square brackets and pass the string in re
, not an integer.
import re input1 = '3787381001' pattern = re.compile('10*1') m = pattern.search(input1) if m: print(m.group())
See Python Demo
Note: if you need to get multiple occurrences with matching matches (for example, if you need to get 1001
and 10001
from 23100100013
), you need to use re.findall(r'(?=(10*1))', input1)
.
source to share