w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python regex search giving none when it should match

What seems to be incorrect:

  1. The result should be printed in the try block.
  2. There is an extra ":" in the except line.

I don't know the exact input format of your line.mesg, so it is possible something is wrong there. But the following code works:

import re

line = '''
(5/12/14 10:22:36 AM EDT) 34438: ##Loading task.##
(5/12/14 10:22:52 AM EDT) 3094962: ##BEEP (375,2)##
(5/12/14 10:22:52 AM EDT) 3095975: ##Aisle One One Seven##;pp
(5/12/14 10:40:07 AM EDT) 4132712: ##Good night.##
'''

regex = re.compile('d{4,}:s##(.*)##')
for line_msg in line.split('
'):
    regex_search = regex.search(line_msg)

    try:
        result = regex_search.group(1)
        print result       # result should be printed here
    except AttributeError: # remove the ":" after "except"
        print regex_search




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.