将多个正则表达式合并到

2024-10-01 07:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个变量:

Application name: Clarion.Pricing.Grid.Service^
Source: EC2AMAZ-ITEJKDI
Timestamp: 2019-01-21T03:52:01.798Z
Message: Connection id ""0HLJV4AI9OCV6"", Request id ""0HLJV4AI9OCV6:000000=
08"": An unhandled exception was thrown by the application.

我想在应用程序名和源代码之后获取字符串,我不擅长正则表达式,所以我创建了两个单独的表达式:

regex1=r'Application name:\s*(.+?)\s+Source'
regex2=r'Source:\s*(.+?)\s+Timestamp:'    
a = re.findall(regex1 ,email_body) 
b = re.findall(regex2 ,email_body) 

如何组合成一个这2个,我需要单独的正则表达式返回字符串后的消息

所需输出

Clarion.Pricing.Grid.Service EC2AMAZ-ITEJKDI Connection id ""0HLJV4AI9OCV6"", Request id ""0HLJV4AI9OCV6:000000=
08"": An unhandled exception was thrown by the application.

Tags: nameanidsourceapplicationrequestserviceconnection
1条回答
网友
1楼 · 发布于 2024-10-01 07:27:08

您可以使用以下正则表达式:

(?:Application name:\s*(.+?)\s+(?=Source))|(?:Source:\s*(.+?)\s+(?=Timestamp:))

说明:您需要使用正向lookahead (?=,这样它就不会使用“Source”字符,否则第二种方法就无法检测到它,通过设计“Timestamp”也是如此,即使它在这里并不重要。(?:用于形成不捕获的regexp组

要添加消息,我假设您希望在输入结束前捕获:

(?:Application name:\s*(.+?)\s+(?=Source))|(?:Source:\s*(.+?)\s+(?=Timestamp:))|(?:Message:\s*([\s\S]*)$)

相关问题 更多 >