Reputation: 73
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).
Upvotes: 0
Views: 120
Reputation: 5291
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
Upvotes: 2
Reputation: 5440
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 r.e. on your example and it runs ok here, so check the above...
Upvotes: 0
Reputation: 691
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)
Upvotes: 0