Repository navigation
Description
Description
In the balancing group (?'g1-g2'exp), when the content matched by exp precedes the latest capture of g2, g1.Captures.Count and the actual behavior of g1 are inconsistent.
By checking the captures of the group using Group.Captures, you will find that the captures appear empty. However, when using (?(g1)yes|no) for conditional evaluation, it will match yes, indicating that there actually is a capture.
更多关于平衡组的bug,可以参考平衡组的bug·其二
For more information about this bug, please refer to Bug in Balancing Groups - Part 2
测试用例中,使用到了比较复杂的正则表达式。
复杂的正则表达式,可视化可参考正则可视化与调试工具
In the test cases, more complex regular expressions are used.
For visualizing and debugging complex regular expressions, you can refer to Regex Visualization and Debugging Tool
Reproduction Steps
using System.Text.RegularExpressions;
string input = "00123xzacvb1";
string pattern=@"\d+((?'x'[a-z-[b]]+)).(?<=(?'2-1'(?'x1'..)).{6})b(?(2)(?'Group2Captured'.)|(?'Group2NotCaptured'.))";
try
{
Match matchInterpreted = new Regex(pattern, RegexOptions.None).Match(input);
Console.WriteLine($"Interpreted Group2: {matchInterpreted.Groups[2].Captures.Count}");
Console.WriteLine($"Interpreted Group2Captured: {matchInterpreted.Groups["Group2Captured"].Captures.Count>0}");
Console.WriteLine($"Interpreted Group2NotCaptured: {matchInterpreted.Groups["Group2NotCaptured"].Captures.Count>0}");
}catch(Exception ex)
{
Console.WriteLine($"Interpreted Exception: {ex.Message}");
}
try
{
Match matchCompiled = new Regex(pattern, RegexOptions.Compiled).Match(input);
Console.WriteLine($"Compiled Group2: {matchCompiled.Groups[2].Captures.Count}");
Console.WriteLine($"Compiled Group2Captured: {matchCompiled.Groups["Group2Captured"].Captures.Count>0}");
Console.WriteLine($"Compiled Group2NotCaptured: {matchCompiled.Groups["Group2NotCaptured"].Captures.Count>0}");
}catch(Exception ex)
{
Console.WriteLine($"Compiled Exception: {ex.Message}");
}
Output:
Interpreted Group2: 0
Interpreted Group2Captured: True
Interpreted Group2NotCaptured: False
Compiled Group2: 0
Compiled Group2Captured: True
Compiled Group2NotCaptured: False
Expected behavior
Interpreted Group2: 1
Interpreted Group2Captured: True
Interpreted Group2NotCaptured: False
Compiled Group2: 1
Compiled Group2Captured: True
Compiled Group2NotCaptured: False
Or
Interpreted Group2: 0
Interpreted Group2Captured: False
Interpreted Group2NotCaptured: True
Compiled Group2: 0
Compiled Group2Captured: False
Compiled Group2NotCaptured: True
Actual behavior
Interpreted Group2: 0
Interpreted Group2Captured: True
Interpreted Group2NotCaptured: False
Compiled Group2: 0
Compiled Group2Captured: True
Compiled Group2NotCaptured: False
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response
Activity
steveharter commentedon Jan 14, 2025
Verified the repro, including verifying generated results via
[GeneratedRegex]match the interpreted and compiled results.However, the repro should be simplified if possible so that it is easier to verify that the result is not correct and to help find the root cause.
Is the discussion at #110976 for issues with
()+?relevant here?FWIW: Generated C# results
longxya commentedon Jan 14, 2025
Discussion at #110976 for issues with
()+?is not relevant here. They are two separate problems, I think.The main problem of the current issue is not the inconsistency between the interpreted mode and the compiled regular expression match results.
However, for the regular expressions raised in the current issue, they do sometimes match inconsistently.
In mircosoft's document Balancing group definitions, when this Balancing grouping construct has the following format:
(?<name1-name2>subexpression)But, what happens if match of
subexpressioncomes beforename2(Groups["name2"].Index)?Both in interpreted and compiled mode,
name1will capture an negative value, butGroups["name1"].Capturesis empty.In this situation, if use
(?(name1)yes|no), or\k'name1',(?'-name1'), it will provoke a series of problems:Group.Captureswill show that the capture group has no captures left.case:
(?'2'\d+)([a-z-[b]]+).(?<=(?'2-1'..).{6})b(?(2)(?'Group2Captured'.)|(?'Group2NotCaptured'.))(?'2')(?'-2')(?'-2')\2match00123xzacvb100123Match.Group[groupName]orMatch.Group[groupNumber]will throw an exception. On the second attempt, it will return null, and all subsequent groups after this group will also be null.case:
(?'2'\d+)([a-z-[b]]+).(?<=(?'2-1'..).{6})b(?(2)(?'Group2Captured'.)|(?'Group2NotCaptured'.))(?'2')(?'-2')(?'-2')(?'-2')match00123xzacvb1expis exactlyLcharacters ahead of the latest capture ofg2, it will cause the currentinputindex to moveLcharacters in the opposite direction of the match.case:
\d+([a-z-[b]]+).(?<=(?'2-1'.).{9})b(?(2)(?'Group2Captured'.)|(?'Group2NotCaptured'.))\2match00123xzacvb1expis exactly two characters ahead of the latest capture ofname2,name1will behave quite "normally". But not entirely normal, after the push and pop operations on Groupname1with(?'name1')(?'-name1'), the properties ofname1are inconsistent before and after the operations.case:
\d+([a-z-[b]]+).(?<=(?'2-1'..).{7})b(?(2)(?'Group2Captured'.)|(?'Group2NotCaptured'.))(?'2')(?'-2')(?(2)(?'Group2Captured'.)|(?'Group2NotCaptured'.))match00123xzacvb21ericstj commentedon Mar 10, 2025
@stephentoub what is your take on this behavior? Is it expected and we just need to document it better, or should we look into balancing groups deeper to see if there is a bug? The docs mention that the balancing group
deletesthe previously defined group - is that why this behavior is observed?FWIW I tested the repo on a few different framework versions and it behaves consistently. I also wasn't sure about group numbering, so I added logging to that. Here's the updated source and output:
Output:
longxya commentedon Mar 12, 2025
@stephentoub @steveharter @ericstj
A new discovery:
In Compiled mode
Output:
Two of the old discoveries:
Output:
Outputt:
steveharter commentedon Mar 13, 2025
Due to the new findings in "Object reference not set to an instance of an object." with compiled, I'll mark this as a bug. The original issue is likely a bug as well, perhaps the same root cause.
The
GroupsCollectionis reporting a count of 8 which should be 1, at least that is what the value is for the interpreted results.GroupsCollection[2]isnullcausing the null ref. However, on the first pass,GroupsCollection[1]throwsIndexOutOfRangeException.4 remaining items
IndexOutOfRangeExceptionorArgumentOutOfRangeExceptionwhen using compiled mode or sourceGeneration, and only thowIndexOutOfRangeExceptionin interpretor #119570 as a duplicate of this issuelongxya commentedon Nov 26, 2025
@stephentoub @ericstj
a balancing group with a capture group can not work normally in
RegexOptions.RightToLeftA regex working in
RegexOptions.RightToLeftis similar to that in positive lookbehind. This would result in a negative-length capture for(?'name1-name2')output(.NET10.0.0):
It seems that Copilot fixed this issue by converting negative-length capture to zero length capture, as what I said in #119570?
Will this fix cause regex patterns like (?'2-1')\d+(?'1') to incorrectly produce zero-length captures for
group#2when using RegexOptions.RightToLeft?stephentoub commentedon Jan 4, 2026
#122836