Skip to content Skip to sidebar Skip to footer

Python Regex Search Giving None When It Should Match

So I have... regex = re.compile('\d{4,}:\s##(.*)##') regex_search = regex.search(line.mesg) # This code is abbreviated. I go on to do things with # 'result' in the

Solution 1:

Ah i see the issue, if you are not tied to using search you can utilise re.findall like in the example below.

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##(.*)##+')
regex_search = regex.findall(line)

try:
   for result in regex_search.groups():
      print result
except AttributeError:
   print regex_search

which returns

['Loading task.', 'BEEP (375,2)', 'Aisle One One Seven', 'Good night.']

Solution 2:

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('\n'):
    regex_search = regex.search(line_msg)

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

Post a Comment for "Python Regex Search Giving None When It Should Match"