-1

Currently, I have this regex for matching content (group 1) inside parenthesis: \((.*?)\)

It is working great, but I would like it to only match the last occurrence of a set of parenthesis:

Test: "(no(yes)"
With my regex the group 1 is no(yes) but I would like it to return yes.

Thank you!

Precision: This is regarding the last set of parenthesis which means that "(no(yes + (1 - 3))" should return yes + (1 - 3)
So \(([^()]+)\) is not working as the content of the last set of parenthesis could contain parenthesis.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
gruvw
  • 725
  • 8
  • 14

1 Answers1

3

Based on your provided examples, you may try this regex:

\(((?:\([^()]*\)|[^()])*)\)[^(]*$

RegEx Demo

RegEx Details:

  • \(: Match a (
  • (: Start capture group
    • (?:: Start non-capture group
      • \([^()]*\): Match a (...) substring
      • |: OR
      • [^()]: Match a character that is not ( and )
    • )*: End non-capture group. Repeat this group 0 or more times
  • ): End capture group
  • \): Match closing )
  • [^(]*: Make sure there is not a ( before end
  • $: End
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • this only works with two levels of nesting. – georg May 09 '21 at 13:47
  • still no luck with `(A ((B)) C)` – georg May 09 '21 at 14:47
  • 1
    @Gruvw: `(A ((B)) C)` has all balanced parentheses but your examples showed unbalanced parentheses and I conformed that in comments as well. As per requirements given this matches `(B)` since that is last pair of `(...)`. If you update your questions with more details I will try to tweak however do keep in mind that Javascript regex does not support recursive pattern matching like PCRE. – anubhava May 10 '21 at 05:49
  • 1
    Nice! @anubhava -I've created [this regex](https://regex101.com/r/odX4ss/1), `(?<=[^(]*\()[^)]*\)(?=\)|$)` which finds the correct match in two of the three strings. At the moment, I am not able to think beyond it, this is where your expertise will be needed. – Arvind Kumar Avinash May 10 '21 at 08:40