我为你写了一个很好的方法。
import re
s = '''
IP Address for: John Doe on 05/20/13
another random string
IP Address for: Jane Doe on 05/20/13
IP Address for: John Appleseed on 05/20/13
random string
IP Address for: Mr. Beans on 05/14/13
IP Address for: Steve Jobs on 05/03/13
IP Address for: Bill Gates on 05/19/13
'''
regex = re.compile(r'IP Address for: (.+) on (\d\d/\d\d/\d\d)')
def method(data, matcher, name=None, date=None):
'''
Takes data and runs the matcher on it to find name and date.
ARGS:
data := the data (string, or fileobject)
matcher := the regex object to match with.
name := specify only specific name to find (optional)
date := specify only specific date to find (optional)
'''
if isinstance(data, str):
content = data.split('\n')
elif isinstance(data, file):
content = data
for line in content:
line = line.strip()
ms = matcher.match(line)
if not ms:
continue
if name and ms.group(1) != name:
continue
if date and ms.group(2) != date:
continue
yield ms.groups()
使用它:
# no options
for result in method(s, regex):
print result
('John Doe', '05/20/13')
('Jane Doe', '05/20/13')
('John Appleseed', '05/20/13')
('Mr. Beans', '05/14/13')
('Steve Jobs', '05/03/13')
('Bill Gates', '05/19/13')
# with a name
for result in method(s, regex, name='John Doe'):
print result
('John Doe', '05/20/13')
# with a date
for result in method(s, regex, date='05/20/13'):
print result
('John Doe', '05/20/13')
('Jane Doe', '05/20/13')
('John Appleseed', '05/20/13')