简体   繁体   中英

Searching and printing regular expression from a file in python

I am using following code in python to search for regular expression in the file, but it keeps returning 'None'. Not understanding what is wrong with it. (Edit- Adding full code)

def process_syslog(file_path):
    with open(file_path, "r") as f:

        for line in f:
           link_down_match = re.search(r'Link Down on en0. (.*$)', line)
           print en0_down_match.group()

link_down_match, always prints 'none'. I am doing RE match for following line:

String to match: Link Down on en0. Reason 1 (Unspecified).

Basically the file I am searching contains multiple such lines mentioned above with 'Reason' being different in some cases (1-10)

This is how I am calling the function from main (snippet)

if current_file == 'syslog':
                curr_file_path = dir_path + str(current_file)
                process_syslog(curr_file_path)

What is wrong here?

Snippet from file I am processing:

Mar 25 06:33:34 ethernet: Status: Link Down on en0. Reason 1 (Unspecified).
Mar 25 06:34:07 ethernet: Status: Link Down on en1. Reason 4 (Unspecified).
Mar 25 06:43:06 ethernet: Status: Link Down on en1. Reason 4 (Unspecified).
Mar 25 06:44:16 ethernet: Status: Link Down on en1. Reason 4 (Unspecified).
Mar 25 06:53:59 ethernet: Status: Link Down on en0. Reason 1 (Unspecified).
Mar 25 06:53:59 ethernet: Status: Link Down on en1. Reason 8 (Unspecified.
Mar 25 16:17:36 ethernet: Status: Link Down on en0. Reason 1 (Unspecified).

updated answer removing the old content:

import re

def process_syslog(file_path):
    with open(file_path, "r") as f:
        for line in f:
            link_down_match = re.search(r'Link Down on en0. (\w+) (\d+)', line)
            if link_down_match == None:
                continue
            print link_down_match.group()

def main():
    process_syslog("syslog.txt")

if __name__ == '__main__':
    main()

Current output:

Link Down on en0. Reason 1

Link Down on en0. Reason 1

Link Down on en0. Reason 1

Change group() to groups()

print link_down_match.groups()

Or

print link_down_match.group(1)
print link_down_match.group(2)
print link_down_match.group(n)

Several things.

  • though you didn't mention it, I suppose you have a 'with open...' statement before the for loop?

  • are you sure you have always exactly 1 space before the (\\w+) and the (\\d+)?

  • you printed the example text with colors in your example. I suppose this is something from Stackoverflow? Else there might be escape sequences in you log.

I tested the re on your example and it runs ok here, so check the above...

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