Reputation: 405
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
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