File tree Expand file tree Collapse file tree 1 file changed +34
-4
lines changed 
src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions Expand file tree Collapse file tree 1 file changed +34
-4
lines changed Original file line number Diff line number Diff line change @@ -233,10 +233,40 @@ internal void BalanceMatch(int cap)
233233        internal  bool  IsMatched ( int  cap ) 
234234        { 
235235            int [ ]  matchcount  =  _matchcount ; 
236-             return 
237-                 ( uint ) cap  <  ( uint ) matchcount . Length  && 
238-                 matchcount [ cap ]  >  0  && 
239-                 _matches [ cap ] [ matchcount [ cap ]  *  2  -  1 ]  !=  ( - 3  +  1 ) ; 
236+             if  ( ( uint ) cap  >=  ( uint ) matchcount . Length  ||  matchcount [ cap ]  ==  0 ) 
237+             { 
238+                 return  false ; 
239+             } 
240+ 
241+             // If not balancing, the simple check suffices 
242+             if  ( ! _balancing ) 
243+             { 
244+                 return  _matches [ cap ] [ matchcount [ cap ]  *  2  -  1 ]  !=  ( - 3  +  1 ) ; 
245+             } 
246+ 
247+             // When balancing is involved, we need to check if there are any real (non-negative) captures 
248+             // that would remain after TidyBalancing compacts the captures. 
249+             // TidyBalancing removes negative (balanced) captures, so we need to count positive ones. 
250+             int [ ]  matcharray  =  _matches [ cap ] ; 
251+             int  limit  =  matchcount [ cap ]  *  2 ; 
252+             int  realCaptureCount  =  0 ; 
253+ 
254+             for  ( int  i  =  0 ;  i  <  limit ;  i  +=  2 ) 
255+             { 
256+                 // Check if this is a real capture (start index is non-negative) 
257+                 if  ( matcharray [ i ]  >=  0 ) 
258+                 { 
259+                     realCaptureCount ++ ; 
260+                 } 
261+                 else 
262+                 { 
263+                     // This is a balancing marker (negative index) 
264+                     // Balancing markers effectively "remove" a previous capture 
265+                     realCaptureCount -- ; 
266+                 } 
267+             } 
268+ 
269+             return  realCaptureCount  >  0 ; 
240270        } 
241271
242272        /// <summary> 
 
 
   
 
     
   
   
          
    
    
     
    
      
     
     
    You can’t perform that action at this time.
  
 
    
  
    
      
        
     
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments