Pythoner
Pythoner

Reputation: 5595

Regex not working properly in linux log4J file?

I have a log file generated by log4j, I want to identify a specific line with regex, which I've tested in regex101.

Here is an example, it matches on regex101:

regex = r"(Batch name): (.*?) (started)"
test_str = "Batch name: AS_ValueOnly started"

But when I iterate over lines in python, this log file could not match with regex. I dig further and found the problem comes from the re.match function, it does not match when the line comes,

import re
log = "test.log"
with open(log, 'rb') as f:
    for line in f.readlines():
        if re.match(r"Batch name", line):
            print "found by regex"
            break
        if "Batch name" in line:
            print 'found by in line'
            break

Here is a runnning result:

$python gen_split_log.py

found by in line

Process finished with exit code 0

Any idea about this?

Upvotes: 0

Views: 54

Answers (1)

Pythoner
Pythoner

Reputation: 5595

Got it, I should use

re.search

not

re.match

Upvotes: 1

Related Questions