Alison LT
Alison LT

Reputation: 405

Non greedy regex within parenthesis and contains text

Suppose I have a string that looks like

test = 'this is a (meh) sentence that uses (random bits of meh2) and (this is silly)'

I want to extract ONLY text inside the parentheses if it includes the word "meh".

Doing a regular non-greedy regex to match anything within parentheses:

re.findall(r'\((.*?)\)', test)

Returns

['meh', 'random bits of meh2', 'this is silly']

Trying to do that to only include the first and second contents:

re.findall(r'\((.*meh.*?)\)', test)

Returns

['meh) sentence that uses (random bits of meh2']

I want a regex to return only

['meh', 'random bits of meh2']

Can someone please help? Thanks!

Upvotes: 3

Views: 1295

Answers (2)

Alison LT
Alison LT

Reputation: 405

re.findall(r'\((.*?meh.*?)\)', test)

Upvotes: 0

Worthwelle
Worthwelle

Reputation: 1271

Instead of allowing all characters, you can allow all characters except the closed parenthesis by using [^\)] where the . is now.

re.findall(r'\(([^\)]*meh[^\)]*?)\)', test)

Upvotes: 4

Related Questions