2

I can match a string from a list of string, like this:

keys = ['a', 'b', 'c']
for key in keys:
    if re.search(key, line):
       break

the problem is that I would like to match a pattern made from regular expression + string that I would specify. Something like this:

keys = ['a', 'b', 'c']
for key in keys:
    if re.search('[^\[]'+key+'[^\]]', line):
       break

but this does not work (in this example I would like to match 'a', 'b' and 'c' only if they appear in squared brackets). I think this has to do with raw strings etc, but I cannot find a way to make it work. Suggestions?

EDIT:

let's say I want to match a pattern a bit more complicated:

'[^\s*data\.'+key+'\s*=\s*\[(.+)[^\]]'

in order to match the number in brackets:

 data.a =  [12343.232 ]
simona
  • 1,799
  • 5
  • 26
  • 38

1 Answers1

3
re.search('\['+re.escape(key)+']', line):

this will match [key]. Note that re.escape was added to prevent that characters within key are interpreted as regex.

Nicolas Heimann
  • 2,501
  • 15
  • 26