简体   繁体   中英

use variable inside regex 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.

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.

Code:

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)

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. Open syslog
  2. Look for the word kernel and NetworkManager
  3. If the beginning of the line is today write to 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.

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

if re.findall(dia, line):
    pass

or something similar:

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.

EDIT: if you are reading strings from the log, you need not (or shouldn't) open them as binary, ie the b flag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM