python重新匹配文件中的字符串

Raj*_*eev 3 python

我想匹配文件中以0D15 开头Characters或仅15位数的所有行。我怎样才能做到这一点

p_number = re.compile(r'(\d{15})')
f=open(infile)
for l in f:
  aa=re.findall(p_number,l)
  if aa > 0:
     print aa
f.close() 
Run Code Online (Sandbox Code Playgroud)

EDIT

如果只有模式在行的开头。

sen*_*rle 5

在行首查找匹配项,请使用re.match。如果0D存在前缀,则此正则表达式匹配所有非空白字符;如果您想匹配较少的字符,请告诉我。

>>> p_number = re.compile(r'(0D[\S]{13}|\d{15})')
>>> for s in ['0Dfannawhoopowe foo', 
              'foo 012345678901234', 
              '012345678901234 foo']:
...     match = p_number.match(s)
...     if match:
...         print match.groups()
... 
('0Dfannawhoopowe',)
('012345678901234',)
Run Code Online (Sandbox Code Playgroud)

对于之间的差异感matchsearchfindall,见下面的例子。

findall (自然地)查找所有匹配项:

>>> for s in ['0Dfannawhoopowe foo', 
              'foo 012345678901234', 
              '012345678901234 foo']:
...     match = p_number.findall(s)
...     if match:
...         print match
... 
['0Dfannawhoopowe']
['012345678901234']
['012345678901234']
Run Code Online (Sandbox Code Playgroud)

search 在字符串中的任何位置查找字符串的出现,而不仅仅是在开头。

>>> for s in ['0Dfannawhoopowe foo', 
              'foo 012345678901234', 
              '012345678901234 foo']:
...     match = p_number.search(s)
...     if match:
...         print match.groups()
... 
('0Dfannawhoopowe',)
('012345678901234',)
('012345678901234',)
Run Code Online (Sandbox Code Playgroud)


Mar*_*Wit 5

import re
with open(infile) as f:
 print re.findall('^(0D.{15}|\d{15})$',f.read(),re.MULTILINE)
Run Code Online (Sandbox Code Playgroud)