2017-04-20 52 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)