Skip to content

Regex.Match with unexpected result when using startat parameter #44444

@lauxjpn

Description

@lauxjpn

I just executed the following lines and expected both Regex.Match() calls to be semantically equal.
However, they are not. While the first one works as expected, the second one fails:

const string fooString = "foo BAR foo";
var regex = new Regex(@"^\w+");

var regexSubstringMatch = regex.Match(fooString.Substring(4)); // regexSubstringMatch.Success == true
var regexStartAtMatch = regex.Match(fooString, startat: 4);    // regexStartAtMatch.Success == false

I consider this behavior unexpected.
Here is a full console project for a quick repro:

using System.Diagnostics;
using System.Text.RegularExpressions;

namespace RegexMatchStartAtIssue
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            const string fooString = "foo BAR foo";
            var regex = new Regex(@"^\w+");

            var regexSubstringMatch = regex.Match(fooString.Substring(4));
            var regexStartAtMatch = regex.Match(fooString, startat: 4);

            Debug.Assert(regexSubstringMatch.Success);
            Debug.Assert(regexSubstringMatch.Value == "BAR");
            Debug.Assert(regexStartAtMatch.Success); // == false
            Debug.Assert(regexStartAtMatch.Value == "BAR");
        }
    }
}

Tested on .NET 5.0.100-rc.2.20479.15.

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