你可以這樣做:
# find lines with authors
import re
# multiline string to simulate possible input
text = '''
Stuff before
This won't be matched...
Author(s) : Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
Other(s) : Something else we won't match
More shenanigans....
Only the author names will be matched.
'''
# run the regex to pull author lines from the sample input
authors = re.search(r'Author\(s\)\s*:\s*(.*?)^[^\s]', text, re.DOTALL | re.MULTILINE).group(1)
上述正則表達式開始的文本匹配(作者(S),空格,冒號,空格),它爲您提供了以下結果由所有行匹配之後即用空格開頭:
'''Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
'''
然後,您可以使用下面的正則表達式組的所有作者從這些結果
# grab authors from the lines
import re
authors = '''Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
'''
# run the regex to pull a list of individual authors from the author lines
authors = re.findall(r'^\s*(.+?)\s*$', authors, re.MULTILINE)
,讓你作者的名單:
['Firstname Lastname', 'Firstname Lastname', 'Firstname Lastname', 'Firstname Lastname']
結合實例代碼:
text = '''
Stuff before
This won't be matched...
Author(s) : Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
Other(s) : Something else we won't match
More shenanigans....
Only the author names will be matched.
'''
import re
stage1 = re.compile(r'Author\(s\)\s*:\s*(.*?)^[^\s]', re.DOTALL | re.MULTILINE)
stage2 = re.compile('^\s*(.+?)\s*$', re.MULTILINE)
preliminary = stage1.search(text).group(1)
authors = stage2.findall(preliminary)
這臺創作者:
['Firstname Lastname', 'Firstname Lastname', 'Firstname Lastname', 'Firstname Lastname']
成功!
你最近在做什麼比賽?編譯,編譯。 – 2011-01-23 22:50:16