Skip to content

Commit 59be2e6

Browse files
Copilotstephentoub
andcommitted
Fix IsMatched to correctly check balancing group state
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
1 parent 58e5b26 commit 59be2e6

File tree

1 file changed

+34
-4
lines changed
  • src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions

1 file changed

+34
-4
lines changed

src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Match.cs

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff 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>

0 commit comments

Comments
 (0)