2011-01-23 225 views
4

我无法将Perl正则表达式转换为Python。我想匹配的文本具有以下模式:将Perl正则表达式转换为Python正则表达式

 
Author(s) : Firstname Lastname 
       Firstname Lastname 
       Firstname Lastname 
       Firstname Lastname 

在Perl中,我能够匹配这个与

/Author\(s\) :((.+\n)+?)/ 

提取作家当我尝试

re.compile(r'Author\(s\) :((.+\n)+?)') 

在Python中,它与第一作者匹配两次,并忽略其余部分。

任何人都可以解释我在这里做错了吗?

+1

你最近在做什么比赛?编译,编译。 – 2011-01-23 22:50:16

回答

3

你可以这样做:

# 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'] 

成功!

+0

谢谢!这很完美! – 2011-01-24 00:38:45

2

一组只能匹配一次。因此,即使您的匹配组重复,您也只能访问上次的实际匹配。你必须一次匹配所有的名字,然后拆分它们(通过换行符,甚至是新的正则表达式)。

+0

谢谢,我基于这个答案的一部分。 – lunixbochs 2011-01-24 00:41:16

1

尝试

re.compile(r'Author\(s\) :((.+\n)+)') 

在原来的表达式中,+?表示要匹配非贪婪,即最小。

相关问题