Skip to content

Regex throws IndexOutOfRangeException or ArgumentOutOfRangeException when using compiled mode or sourceGeneration, and only thow IndexOutOfRangeException in interpretor #119570

Closed as duplicate

Description

@longxya

Description

The pattern created together with the original pattern of issue#119444, throw a differnet exception IndexOutOfRangeException. I think the reason of appearing ArgumentOutOfRangeException is some different with issue#119444. Actually, current original pattern cames earlier than issue#119444.

this is the original pattern of current issue `^(?=\d{3,12})(?'time'){12}(((?=(?>(?'-time')(?'y')|(?'x')){12}(?>(?'time-y')|){12}((^[1-9](?'count')((?>(?'x11-x1'))\d(?'count')||(?>(?'-x')|(?'x1'))\d(?'count')){2}(?>(?'x1-x11')|){2}|0)(?=(?>\d{3,9})$)(?((?'-count'){3})(?(?'-count')|){3})([1-9](?'count')((?>(?'x22-x2'))\d(?'count')||(?>(?'-x')|(?'x2'))\d(?'count')){2}(?>(?'x2-x22')|){2}|0)(?=(?>\d{2,6})$)(?((?'-count'){3})(?(?'-count')|){3})([1-9](?'count')((?>(?'x33-x3'))\d(?'count')||(?>(?'-x')|(?'x3'))\d(?'count')){2}(?>(?'x3-x33')|){2}|0)(?=(?>\d{1,3})$)(?((?'-count'){3})(?(?'-count')|){3})(?(\d\d\d$)(?![3-9]\d\d|\d([6-9]\d|5[6-9])))([1-9]\d*|0)$(?!(?'-x'))(?>(?'-x')|){12}))|)(?'-time')){12}`

I simplified it to (?'time'){2}(?=(?>(?'-time')|(?'x')){3}((((?'x22-x2')|(?>(?'-x')|(?'x2')))\d){2}((?'-x22')(?'x2')|))){2}. I used my website to find that it was probably because tried to balance group#x22 after group#x22 got a negative-length capture during the matching process.
Based on this reason, I constructed some simpler patterns.

Current issue is related to issue#111161.
There is also an IndexOutOfRangeException in issue#111161, but it cames after the sucess match, different from current situation that occurs during the matching process.

Reproduction Steps

using System;
using System.Text.RegularExpressions;
{
	string pattern = @"(?=.....())(?'2-1')\2";
	string input = "12345";
	Regex regex = new Regex(pattern, RegexOptions.Compiled);
	var mhes = regex.Matches(input);
	try
	{
		Console.WriteLine(mhes.Count);
	}catch(Exception e)
	{
		Console.WriteLine("Compiled : "+e.Message);
	}
	try
	{
		Console.WriteLine(Regex.Matches(input,pattern).Count);
	}catch(Exception e)
	{
		Console.WriteLine("Interpretor : "+e.Message);
	}
}
{
	string pattern = @"(?=.....())(?'2-1')(?'2')(?'-2')\2";
	string input = "12345";
	Regex regex = new Regex(pattern, RegexOptions.Compiled);
	var mhes = regex.Matches(input);
	try
	{
		Console.WriteLine(mhes.Count);
	}catch(Exception e)
	{
		Console.WriteLine("Compiled : "+e.Message);
	}
	try
	{
		Console.WriteLine(Regex.Matches(input,pattern).Count);
	}catch(Exception e)
	{
		Console.WriteLine("Interpretor : "+e.Message);
	}
}

Expected behavior

Whatever, just don't as same as the actual output.

Actual behavior

Compiled : Index was outside the bounds of the array.
Interpretor : Index was outside the bounds of the array.
Compiled : Specified argument was out of the range of valid values.
Interpretor : Index was outside the bounds of the array.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

Activity

  1. added
    untriaged
    on Sep 11, 2025
  2. dotnet-policy-service commented on Sep 11, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-text-regularexpressions
    See info in area-owners.md if you want to be subscribed.

  3. longxya commented on Sep 11, 2025

    @longxya
    Author

    Using (?=.....())(?'2-1')\2 or (?=.....())(?'2-1')(?'-2') to match 123456, throw Index was outside the bounds of the array..
    Because the execution of operations \2 and (?'-2') both use Match.MatchLength(2).
    Here is the code of Match.MatchLength(). I added some analysises:

            /// <summary>
            /// Returns the length of the last specified matched group by capnum
            /// </summary>
            internal int MatchLength(int cap)
            {
                int[][] matches = _matches;
    
    			//matches[cap].Length = 2  it's cause is Group#2 has only one capture (5,-5)
                int i = matches[cap][_matchcount[cap] * 2 - 1];
    			// i = -5 => 
    			//	-3 - i = 2  but max Index of matches[cap] just can be 1
    			//so matches[cap][2] throw IndexOutOfRangeException
                return i >= 0 ? i : matches[cap][-3 - i];
            }

    In compiled mode and Source Generated code, using (?=.....())(?'2-1')(?'2')(?'-2')\2 to match 12345, throw Specified argument was out of the range of valid values.
    Here is the code of Match.MatchLength(). I also added some analysises:

            /// <summary>
            /// Returns the length of the last specified matched group by capnum
            /// </summary>
            internal int MatchLength(int cap)
            {
                int[][] matches = _matches;
    
    			//matches[cap].Length = 6  cause Group#2 captures : 
    			//(5,-5) (0,0) (-1,-2)  not all is capture,some is balance
                int i = matches[cap][_matchcount[cap] * 2 - 1];
    			// i = -2 => 
    			//	-3 - i = 1  but matches[cap][1] = -5
                return i >= 0 ? i : matches[cap][-3 - i];//still return a negative number
    			//this is the point, but it wouldn't throw exception any more
            }

    ArgumentOutOfRangeException was thrown when using \2 at the end:

    matchLength = base.MatchLength(2);//-5
    //slice = "12345"
    if (slice.Length < matchLength || 
    	//inputSpan.Slice(5, -5) throw ThrowArgumentOutOfRangeException
        !inputSpan.Slice(base.MatchIndex(2), matchLength).SequenceEqual(slice.Slice(0, matchLength)))
    {
        UncaptureUntil(0);
        return false; // The input didn't match.
    }

    In issue#113734, in compiled mode, using \d+(?'1'.)(?<=(?'2-1'.).{5})\2to match WTF123a1, will cause infinite matches.
    But it still throw Specified argument was out of the range of valid values. in Source Generated code.
    It because Length of Group#2's Capture is -4,(-3 - (-4)) = 1. It happens to be the index of the last element of matches[cap]. So Match.MatchLength(2) wouldn't throw, but inputSpan.Slice(base.MatchIndex(2), matchLength) will.

    I don't konw why that pattern will cause infinite matches instead of thow exception in compiled mode.
    What I konw is, in compiled pattern, when group#2 got a negative-length capture, if not throw exception when match steps came to \2, back reference of this group will cause the current match index of input(textpos), move negative length(length of capture), aka move ABS(negative-length of group#2's value) character lengths in the opposite direction of the match(as what I said in issue#113734). And differnet with (?<=), it wouldn't reset textpos.

    But change the pattern to \d+(?'1'.)(?<=(?'2-1'.).{6})\2, will thow Index was outside the bounds of the array. in compiled mode and Source Generated code.
    And compiled pattern \d+(?'1'.)(?<=(?'2-1'.).{6})(?'2')(?'-2')\2 cause infinite matches again.
    And in Source Generated code, of course, \d+(?'1'.)(?<=(?'2-1'.).{6})(?'2')(?'-2')\2 still throw Specified argument was out of the range of valid values.

    **Attention : **
    In the issue#119444,Source Generated code work normally in .net9, but doesn't in .net10(Source Generated in .net10)

  4. stephentoub commented on Sep 11, 2025

    @stephentoub
    Member

    There's no situation where running a regex should result in any such exception. The bug is that an exception is being thrown, not which exception is thrown. You've opened a few issues; is the fact that an exception is being thrown covered by one of those? If so, this one can be closed.

  5. longxya commented on Sep 12, 2025

    @longxya
    Author

    There's no situation where running a regex should result in any such exception.

    I see. I think Regex.Matches(input, pattern) shouldn't throw any exception besides pattern error.

    is the fact that an exception is being thrown covered by one of those?

    What do u mean?
    I did report an IndexOutOfRangeException in issue#111161, but there are some differences in how they are triggered, although they are all based on negative-length capture.

    Regarding the current issue(issue#119570)、issue#118666、issue#111161 and issue#113734.
    I think the root cause of these four issues is a group catching a negative-length capture.
    It looks like they are all because (?<=(?'2-1')exp) or (?=exp(?'2-1')) could cause group#2 to get a negative-length capture, which leads to a series of issues.
    I don't know how you plan to deal with groups which could catch negative-length captures.

    ‌I have a half-baked suggestion. If set capture to 0(index += length;length = 0;) when a group gets a negative-length capture, these four issues might be solved.
    After all, groups with negative-length capture seem to have no value in backreference; they might be used as a counter only.
    But if u don't, they might need different approaches to solve. That's why I opened different issues.
    For issue#113734, infinite matches smell very dangerous, so created a separate issue.

    About issue#119444, I can't find any connection between it and negative-length capture. But I can't say for sure.

    So if I discover more issues regarding negative-length capture groups after this, shall I comment on issue#111161 ?

    Or if I find that regex throws any different exceptions, should I comment on them in one issue?
    For example, should the Bad label content in ILGenerator. and the current two exceptions be discussed in one issue if discovered at the same time?

  6. stephentoub commented on Sep 12, 2025

    @stephentoub
    Member

    I think the root cause of these four issues is a group catching a negative-length capture.

    Thanks. Then we should just use one issue for all of them and close this and the others.

  7. longxya commented on Sep 12, 2025

    @longxya
    Author

    all of them

    Just negative-length capture issues? or all regex issues?

    And what I mentioned, in the issue#119444, Source Generated code work normally in .net9, but doesn't in .net10(Source Generated in .net10)
    Here is summary of source generated:

    partial class C
    {
        /// <remarks>
        /// Pattern:<br/>
        /// <code>(?'time'){2}(?=((?'-time')|(?'x')){3}(((?'count')(((?'-count')|((?'-x')))(?'count')){2}|0)(?((?'-count'){3})|((?'-count')|){3})(?!(?'-x')))|){2}</code><br/>
        /// Explanation:<br/>
        /// <code>
        /// ○ Loop exactly 2 times.<br/>
        ///     ○ "time" capture group.<br/>
        ///         ○ Match an empty string.<br/>
        /// ○ Loop exactly 2 times.<br/>
        ///     ○ Zero-width positive lookahead.<br/>
        ///         ○ Optional (greedy).<br/>
        ///             ○ Loop exactly 3 times.<br/>
        ///                 ○ 1st capture group.<br/>
        ///                     ○ Match with 2 alternative expressions.<br/>
        ///                         ○ Non-capturing balancing group. Uncaptures the "time" capture group.<br/>
        ///                             ○ Match an empty string.<br/>
        ///                         ○ "x" capture group.<br/>
        ///                             ○ Match an empty string.<br/>
        ///             ○ 2nd capture group.<br/>
        ///                 ○ Fail to match.<br/>
        /// </code>
        /// </remarks>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Text.RegularExpressions.Generator", "10.0.12.42804")]
        public static partial global::System.Text.RegularExpressions.Regex YourRegex() => global::System.Text.RegularExpressions.Generated.YourRegex_0.Instance;
    }

    It says

        ///         ○ 2nd capture group.<br/>
        ///             ○ Fail to match.<br/>

    But in the interpreter, Group#2 does have captures.

    Should this source generated issue be commented on issue#119444? or open a new issue? or together with negative-length capture issues?

  8. stephentoub commented on Sep 15, 2025

    @stephentoub
    Member

    Just negative-length capture issues? or all regex issues?

    Everything with likely the same root cause should be a single issue.

  9. longxya commented on Sep 16, 2025

    @longxya
    Author

    OK.

    Current issue(issue#119570)、issue#118666 and issue#113734] could be closed,
    and information of the three issues could be summarized in issue#111161.

    About issue#119444, it's probably not caused by negative-length.

  10. removed
    untriaged
    on Sep 24, 2025
  11. locked and limited conversation to collaborators on Oct 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions