3

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 ]
9
  • Then use re.search(r'\[{}]'.format(key), line). Or if r'[{}]'.format(key) in line:. See ideone.com/UimIyJ Commented Jul 14, 2016 at 13:14
  • 1
    "... I would like to match [...] if they appear in squared brackets" Then why have you negated the square brackets? Commented Jul 14, 2016 at 13:15
  • what about if I want to match something more complicated? like in the edit I have made Commented Jul 14, 2016 at 13:15
  • What edit do you mean? Please provide a test case. Commented Jul 14, 2016 at 13:17
  • @IgnacioVazquez-Abrams because I want to match only what appears in the brackets Commented Jul 14, 2016 at 13:18

1 Answer 1

4
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.

Sign up to request clarification or add additional context in comments.

3 Comments

You do not need to escape ].
Thank for the hint, but, are you sure? What if key=abc, then the regex would be '[abc]' witch matches any a, b, or c? What do I miss here?
No, the [ must be escaped, and ] does not have to.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.