AndresR
AndresR

Reputation: 608

Capture the contents of a sequence of matching parenthesis with a regex expression

I have the following text:

y=asin(pi*2*(vel_rot+(dan_int+didt)/2.));

I want a regex expression capturing the parameters to the function asin, i.e, in the example, it should match:

pi*2*(vel_rot+(dan_int+didt)/2.)

My issue is that I dont know how to skip as many closing parenthesis as opening parenthesis I find

Upvotes: 1

Views: 35

Answers (1)

user557597
user557597

Reputation:

Use a PCRE(or Perl) style engine that supports recursion.
Or, you can use Dot-Nets counting group to navigate nesting.

This is the former.

y=asin(\(((?:[^()]++|(?1))*)\))

Explained

 y=asin
 (                       # (1 start), Recursion code group
      \(
      (                       # (2 start), Capture, inner core
           (?:                     # Cluster group
                [^()]++                 # Possesive, not parenth's
             |                        # or,
                (?1)                    # Recurse to group 1
           )*                      # End cluster, do 0 to many times
      )                       # (2 end)
      \)
 )                       # (1 end)

Output

 **  Grp 0 -  ( pos 0 , len 40 ) 
y=asin(pi*2*(vel_rot+(dan_int+didt)/2.))  
 **  Grp 1 -  ( pos 6 , len 34 ) 
(pi*2*(vel_rot+(dan_int+didt)/2.))  
 **  Grp 2 -  ( pos 7 , len 32 ) 
pi*2*(vel_rot+(dan_int+didt)/2.)  

Upvotes: 2

Related Questions