Regex - Match last occurrence of parentheses

Viewed 316

In the below string I am trying to get the substring (2005, Penguin Classics) substring.

Marshall B. Rosenberg PhD - The Surprising Purpose of Anger_ Beyond Anger Management_ Finding the Gift (Nonviolent Communication Guides) (2005, Penguin Classics) AAA.pdf

I am doing this to change the substring to just (2005).

Below is my current solution but it matches both (Nonviolent Communication Guides) and (2005, Penguin Classics). Any ideas on how to fix this?

import re

parentheses_pattern = "\(([^)]+)\)*$"
reg = re.search(parentheses_pattern, filename)
year = reg.group()
year = year[:5]+")"
filename = re.sub(parentheses_pattern,year,filename)
2 Answers

Would this work maybe?

\(\d+, .*\)

A good place to test your regex is this: https://rubular.com/

Just in case it comes in handy! :)

Perhaps this will help:

r"\(([^\)]+)\)[^\(]*$"
Related