簡體   English   中英

將Perl正則表達式轉換為Python正則表達式

[英]Converting Perl Regular Expressions to Python Regular Expressions

我在將Perl正則表達式轉換為Python時遇到了麻煩。 我想要匹配的文本具有以下模式:

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

在perl中我能夠匹配這個並提取作者

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

當我嘗試

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

在Python中,它匹配第一個作者兩次並忽略其余的。

誰能解釋我在這里做錯了什么?

你可以這樣做:

# 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)

上面的正則表達式匹配起始文本(作者,空格,冒號,空格),它通過匹配后面以空格開頭的所有行給出了下面的結果:

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

成功!

一組只能匹配一次。 因此,即使您的匹配組重復,您也只能訪問上一次實際匹配。 您必須一次匹配所有名稱然后將它們拆分(通過換行或甚至新的正則表達式)。

嘗試

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

在你的原始表達中, +? 表示你希望比賽非貪婪,即最小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM