Python:在一个命令中搜索两个正则表达式

时间:2017-04-14 19:01:47

标签: python

如何在一个findall命令中搜索两个正则表达式?我有一个丑陋的程序来完成这项工作,但我想学习更好的Python方法来做到这一点。

在下面的例子中,我想识别所有服务器(alarm1 side0& alarm1 side1)OR(问题2)。

档案:

Server 1, side 0, Alarm 1
Server 1, side 1, Alarm 1
Server 1, Problem 2
Server 2, Alarm 2
Server 3, side 0, Alarm 1
Server 4, side 1, Alarm 1
Server 5, Alarm 3

预期产出:

Server 1, Alarm 1, Alarm 2
Server 2, Alarm 2

脚本:

#! /usr/bin/python
import re
import sys
import os

def main():
  server_alarm_list=[]
  with open('sample_data') as f:
    text=f.read()
    Alarm1_side0_tuple=re.findall(r'Server (\d+), side 0, Alarm 1', text)
    Alarm1_side1_tuple=re.findall(r'Server (\d+), side 1, Alarm 1', text)
    Alarm2_tuple=re.findall(r'Server (\d+), Problem 2', text)
    for i in Alarm1_side0_tuple:
      if i in Alarm1_side1_tuple:
        server_alarm_list.append(i)
     for i in Alarm2_tuple:
       if i in server_alarm_list:
         print "Server" + i + ", Alarm 1, Alarm 2"
       else:
         print "Server" + i + ", Alarm2"


if __name__ == '__main__':
    main()

0 个答案:

没有答案