Skip to content

Regex evaluation bug - discrepancy between compiled and non-compiled regex #97455

@lahma

Description

@lahma

Description

Running same Regex as compiled and non-compiled version is producing different outcome.

Reproduction Steps

using System.Text.RegularExpressions;

namespace BugReport;

public class RegexTests
{
    [Fact]
    public void CompiledRegexShouldProduceSameResultAsNonCompiled()
    {
        const string Pattern = @"(.*?)a(?!(a+)b\2c)\2(.*)";
        var nonCompiled = new Regex(Pattern, RegexOptions.None);
        var compiled = new Regex(Pattern, RegexOptions.Compiled);

        const string Input = "baaabaac";
        const int GroupNumber = 2;

        Assert.Equal(nonCompiled.Match(Input).Groups[GroupNumber].Value, compiled.Match(Input).Groups[GroupNumber].Value);
    }
}

Expected behavior

Group capture is equal, in this case value should be empty.

Actual behavior

Xunit.Sdk.EqualException
Assert.Equal() Failure: Strings differ
Expected: ""
Actual:   "a"
           ↑ (pos 0)
   at CompiledRegexShouldProduceSameResultAsNonCompiled() in Test.cs:line 18
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)

Regression?

No response

Known Workarounds

No response

Configuration

Runnin latest .NET, Windows 11.

❯ dotnet --version
8.0.101

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions