[Python] Regex - Match last occurrence of parentheses

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    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)

    Continue reading...

Compartilhe esta Página