在正则表达式python中使用变量 [英] use variable inside regex python

查看:54
本文介绍了在正则表达式python中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

值得离开这里,这是我在 Python 中的第二天,我对这门语言不是很专业.任何低级建议和易于理解将不胜感激.

It's worth leaving here that this is my second day in Python and I'm not very pro at this language. Any low level suggestion and easy to understand would be much appreciate.

我想在 python 的正则表达式中使用一个变量.我已经阅读了这个问题如何在正则表达式中使用变量?回答.

I would like to use a variable inside a regex in python. I have read this question How to use a variable inside a regular expression? without any luck in the answer.

代码:

import time
import re

dia = time.strftime('%b %d')

final = open('/root/final.txt', 'ab')
file = open('/var/log/syslog', 'rb')

for line in file:
    if re.findall('kernel|\bNetworkManager\b', line):
        if re.findall(r'dia', line):
            final.write(line)

有很多我认为与问题无关的代码.我也试过这个解决方案 if re.findall(r'%s'%dia, line) 没有运气.

There's a lot of code that I don't think is relevant to the question. I have tried this solution as well if re.findall(r'%s'%dia, line) with no lucky.

既然我在这里,我想解释一下我的想法,看看我的方向是否正确:

Since I'm in here i would like to explain my thought and see if I'm in the right direction:

  1. 打开系统日志
  2. 寻找词 kernel 和 NetworkManager
  3. 如果行的开头是今天,则写入 final.

提前致谢.祝你有一个美好的一年.

Thanks in advance. Wish you a great year.

推荐答案

不能在字符串中引用变量.字符串只是文本,它不知道名称空间,解释器也不会为它解析.

You can't reference a variable in a string. A string is just text, it has no knowledge of the namespace, and the interpreter does not resolve that for it.

因为你的变量 dia 是一个字符串,你可以在调用 re.findall 时使用它:

Since your variable dia is a string, you can just use that in your call to re.findall:

if re.findall(dia, line):
    pass

或类似的东西:

if re.findall(r"{0}".format(dia), line):
    pass

至于您所做操作的正确性,如果日志上的时间戳格式与您使用的相同,则应该是正确的.

As for that correctness of what you're doing, if format of the time stamp on the log is the same what you're using, it should be correct.

如果您从日志中读取字符串,则不需要(或不应该)以二进制形式打开它们,即 b 标志

if you are reading strings from the log, you need not (or shouldn't) open them as binary, i.e. the b flag

这篇关于在正则表达式python中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆