Search code examples
regexnintex-workflow

RegEx to Match Everything Up To And Including the Last Parentheses


I have a string of text like this:

Bob Smith (Approve) Request reviewed 4/27/2016 (Bob Smith) Have fun on your vacation!

And I want to use a regular expression to match everything up to and including the last parentheses, which would be this:

Bob Smith (Approve) Request reviewed 4/27/2016 (Bob Smith)

I am eventually going to use this regular expression to replace the text up to and including the last parentheses with nothing, so that only the comment at the end is returned. (It would be easier to match on the part after the last parentheses [see below], but I am using a different approach based on a quirk in the program I'm using.)

I found this question on SO that asks about how to find everything after the last forward slash: Regular Expression for getting everything after last slash. The answer is:

([^/]+$)

However, I need to modify that regular expression to find everything UP TO AND INCLUDING the last PARENTHESES. I tried to modify to this:

(^[^)]+) 

but that finds everything up to but NOT INCLUDING the FIRST parentheses.

How can I change that to match everything up to and including the last parentheses?

See this RegExr as an example: http://regexr.com/3dahe


Solution

  • I want to use a regular expression to match everything up to and including the last parentheses

    You just need greedy dot matching:

    ^.*\)\s*
    

    See the regex demo

    Use a DOTALL modifier if there are newline symbols in the input.

    Pattern details:

    • ^ - start of string
    • .* - any 0+ characters other than a newline up to the last
    • \) - closing parentheses
    • \s* - 0+ whitespaces.