2

I know this is a very frequently asked question, but it's driving me mad.

I want to use regex to match a substring in my string.

 line = '##ParameterValue[part I care about]=garbagegarbage'

And I would like to extract the part I care about. My code looks like this:

import re
line = '##ParameterValue[part I care about]=garbagegarbage'
m = re.match('\[(.*)\]', line)
print m.group(1)

But this gives me an AttributeError: 'NoneType' object has no attribute 'group'

I tested my regex on regex101 and it works. I don't understand why this fails for me.

Jack
  • 722
  • 3
  • 8
  • 24
  • 2
    You are right, it is too frequent a question. – Wiktor Stribiżew Apr 20 '17 at 20:26
  • 1
    Try [`search`](https://docs.python.org/2/library/re.html#re.search) instead. [`match`](https://docs.python.org/2/library/re.html#re.match) is looking to match from beginning of the string. – double_j Apr 20 '17 at 20:29

1 Answers1

9

Change match to search

import re
line = '##ParameterValue[part I care about]=garbagegarbage'
m = re.search('\[(.*)\]', line)
print m.group(1)
depperm
  • 10,606
  • 4
  • 43
  • 67