Евгений Мичурин Евгений Мичурин - 11 months ago 77
Python Question

Regular expression extract specific part

I have a string

. The presence of the word
is necessary.

re.search('skip[(].+[)]', args[0]).group(0)

gives me
, but not
. I can could use slicing
to get
, but it's too clumsy

What the easiest way to get only the value in brackets ('test774') using regular expressions?

cco cco
Answer Source

To isolate the text you want, use a capturing group around the part of the regex that matches that text.

re.search('skip[(]([^)]+)[)]', args[0]).group(1)

The change I made is where you have .+ (any non-empty sequence of characters), I have ([^)]+) (a capturing group containing a non-empty sequence of characters other than ); this means this part of the match stops just before the first ), rather than just before the last ), as .+ would).

regex101.com demo and explanation