2017-04-20 51 views
0

Python的正則表達式匹配我有以下內容的日誌文件爲多行文本

commit da83ddfdfb36f0c48ab2137efaa8c81a6bb41993 
Author: 」abc <[email protected]> 
Commit: 」abc <[email protected]> 
.. 
.. 

我想創建正則表達式匹配的表達式如下

TEST_COMMIT = 'commit\ (?P<commit>[a-f0-9]+)\n(?P<author>Author.*)\n' 
RE_COMMIT = re.compile(TEST_COMMIT, re.MULTILINE | re.VERBOSE) 

這符合上regex101罰款(https://regex101.com/)但在我的代碼中不起作用。

我想要提交ID和作者信息作爲單獨的組表達式。 所以

commit group should be : `da83ddfdfb36f0c48ab2137efaa8c81a6bb41993` 
author group should be : `Author: 」abc <[email protected]> 

我的Python版本是2.7.12

什麼我做錯了什麼意見嗎?

回答

1

最後,我已經能夠解決這個問題。

問題是日誌文件的新行是回車+新行。 \ r \ n

將正則表達式更改爲包含\ r \ n後,其能夠正確獲取正則表達式組。此代碼正在工作

TEST_COMMIT = r''' 
commit\ (?P<commit>[a-f0-9]+)\r\n 
(?P<author>Author.*)\r\n' 
(?P<committer>Commit.*)\r\n' 
(?<message>.*)\r\n 
) 
''' 
RE_COMMIT = re.compile(TEST_COMMIT, re.MULTILINE | re.VERBOSE) 

commits = RE_COMMIT.finditer(data)