使用Python 3在输入中搜索模式时出错



我正在尝试找出输入号码中 1[0]1的模式数量。该模式是,,在两个1的之间可以有任何数量的零,如893 10001 898。

我编写了一个代码,使用正则表达式( re (在Python 3.5中执行此代码,如下所示:

>>> import re
>>> input1 = 3787381001
>>> pattern = re.compile('[10*1]')
>>> pattern.search(input1)

但这给我带来了以下错误

Traceback (most recent call last):
   File "<pyshell#8>", line 1, in <module>
     pattern.match(input1)
TypeError: expected string or bytes-like object

是否有一些解决方法可以清楚地识别上述模式1[0]1是否存在输入号中?

[10*1]模式匹配一个等于 10*的字符。另外,正则发动机仅在文本中寻找匹配项,它需要一个字符串作为输入参数。

卸下方括号,然后将字符串传递到re,而不是整数。

import re
input1 = '3787381001'
pattern = re.compile('10*1')
m = pattern.search(input1)
if m:
    print(m.group())

请参阅Python Demo

注意:如果需要进行多次出现,则具有重叠匹配(例如,如果需要从23100100013获取100110001(,则需要使用re.findall(r'(?=(10*1))', input1)

最新更新