如何使用正则表达式搜索来搜索变量值

时间:2015-01-20 04:04:37

标签: python regex

我有多行,我只需要选择那些包含特定值的行。 例如,

[DEBUG] 2014-12-01 16:39:12,049 [1984] Agent Logger Initialized
[DEBUG] 2014-12-01 16:39:12,049 [2884] Agent Logger Initialized
[DEBUG] 2014-12-01 16:39:12,049 [2884] Agent Actuation Logger Initialized

所以我有一个变量var = 1984。

id=re.search(r'\[var\],s,re.I|re.M|re.S)
if id:
   print line

上面的正则表达式只能搜索var = 1984并且应该打印包含该值的行" [1984]"。有人建议怎么做吗?我需要这个在Linux中搜索我正在使用Python 2.6。

3 个答案:

答案 0 :(得分:0)

这个正则表达式应该有效:

var=1984
reg = '.+'+str(var)+'.+'
id=re.search(reg,s,re.I|re.M|re.S)

或简单:

import re

s = ['[DEBUG] 2014-12-01 16:39:12,049 [1984] Agent Logger Initialized',
     '[DEBUG] 2014-12-01 16:39:12,049 [2884] Agent Logger Initialized',
     '[DEBUG] 2014-12-01 16:39:12,049 [2884] Agent Actuation Logger Initialized']

var = 1984
for line in s:
    id = re.findall(r'.+%d.+' % var, line, re.I | re.M | re.S)
    if id:
        print line

输出:

[DEBUG] 2014-12-01 16:39:12,049 [1984] Agent Logger Initialized

答案 1 :(得分:0)

您也可以使用简单的if条件来执行此操作:

from io import StringIO

text = StringIO(u"""\
[DEBUG] 2014-12-01 16:39:12,049 [1984] Agent Logger Initialized
[DEBUG] 2014-12-01 16:39:12,049 [2884] Agent Logger Initialized
[DEBUG] 2014-12-01 16:39:12,049 [2884] Agent Actuation Logger Initialized
""")

for line in text:
    if '[1984]' in line:
        print line

[DEBUG] 2014-12-01 16:39:12,049 [1984] Agent Logger Initialized

答案 2 :(得分:0)

这应该有效:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
var = '\[1984\]'
with open("test.log")  as fp: # assuming your log file is test.log
    lines = fp.readlines()
    for line in lines:
        line = line.strip()
        if re.match(r'.*'+str(var)+'.*',line): # may be you want to add some more strict matching rules here.
            print line

# vim:ai:et:sts=4:sw=4: