我正在使用正则表达式提取某些模式,但是似乎findall
方法在不同的时间针对相同的字符串和模式返回了不同的结果。
首先,它找不到任何匹配对象并返回空列表,然后在我一次构建模式对象时一次一组(模式对象由三组组成)并每次应用findall
方法它返回真实结果。
在最后一步(我将具有与开始步骤相同的模式),即使它与返回空列表的模式对象是同一模式对象,它也会返回预期结果
我不确定是否要丢失一些东西,有人可以解决这个强大的问题吗
我不太会在这里提出问题,如果有不清楚的地方,请指出
In[98]: a[1] # a string object from list "a"
Out[98]: 'c48: 1777'
In[99]: a_re= re.compile('r(c[0-9]+)(: )(.*)') # pattern object
In[100]: a_re.findall(a[1])
Out[100]: []
In[101]: a_re= re.compile(r'(c[0-9]+)')
Out[102]: a_re.findall(a[1])
Out[102]: ['c48']
In[103]: a_re= re.compile(r'(c[0-9]+)(: )')
In[104]: a_re.findall(a[1])
Out[104]: [('c48', ': ')]
In[105]: a_re= re.compile(r'(c[0-9]+)(: )(.*)')
In[106]: a_re.findall(a[1])
Out[106]: [('c48', ': ', '1777')]
答案 0 :(得分:0)
这只是一个较小的错字,即使您可以这样称呼。像这样将r
放在字符串之外:
a_re= re.compile(r'(c[0-9]+)(: )(.*)')
答案 1 :(得分:0)
代码:
import re
print(re.findall(r'(c[0-9]+)(: )(.*)','c48: 1777'))
输出:
[('c48', ': ', '1777')]
达到相同的结果。