Skip to content

Regex: under the default p flag a negated bracket like [^x] never matches a newline #4156

Not planned

Description

@CaffeinatedCoder
Environment
PostgreSQL 18.6 (postgres:18), session TimeZone Etc/UTC
.NET 10 runtime 10.0.15, Npgsql.EntityFrameworkCore.PostgreSQL 10.0.4, EF Core 10.0.15, Npgsql 10.0.4
.NET 11 runtime 11.0.0, Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0, EF Core 11.0.0, Npgsql 11.0.0
Also macOS arm64

Both lines print the same output. main at 9a76cd8 has the same code.

Split from #4094 at your request.

Without options, the pattern gets the p flag so that . doesn't match a newline, as in .NET. But p also stops a negated bracket from matching a newline, and .NET's [^x] does match \n.

LINQ Input .NET PostgreSQL SQL
Regex.IsMatch(r.Text, "a.b") a\nb no match no match r."Text" ~ '(?p)a.b'
Regex.IsMatch(r.Text, "a[^x]b") a\nb match no match r."Text" ~ '(?p)a[^x]b'
Repro
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;

await using var context = new TestContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

context.Rows.Add(new Row { Text = "a\nb" });
await context.SaveChangesAsync();
var rows = await context.Rows.AsNoTracking().ToListAsync();

// Without RegexOptions.Singleline, . doesn't match \n but a negated bracket does
Console.WriteLine($"IsMatch(\"a\\nb\", \"a.b\"): .NET {rows.Count(r => Regex.IsMatch(r.Text, "a.b"))}, database {await context.Rows.CountAsync(r => Regex.IsMatch(r.Text, "a.b"))}");
Console.WriteLine($"IsMatch(\"a\\nb\", \"a[^x]b\"): .NET {rows.Count(r => Regex.IsMatch(r.Text, "a[^x]b"))}, database {await context.Rows.CountAsync(r => Regex.IsMatch(r.Text, "a[^x]b"))}");

public class TestContext : DbContext
{
    public DbSet<Row> Rows => Set<Row>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql(Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"))
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();
}

public class Row
{
    public int Id { get; set; }
    public string Text { get; set; } = "";
}

Output, the same on both lines:

IsMatch("a\nb", "a.b"): .NET 0, database 0
IsMatch("a\nb", "a[^x]b"): .NET 1, database 0

The flag is chosen at NpgsqlQuerySqlGenerator.cs#L1058-L1062. PostgreSQL has no flag where . excludes newlines but [^…] includes them (p and n restrict both, s and w neither), so matching .NET exactly would mean rewriting a constant pattern (. → [^\n] with no flag). If that's not wanted, a docs note on the regex translation would make the difference visible.

Activity

  1. roji commented on Nov 25, 2026

    @roji
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Confirmed semantic mismatch in supported released Npgsql providers and current main. My recommendation is to document the dialect limitation rather than introduce automatic pattern rewriting for this issue. This is distinct from the simple combined-options mapping defect in #4155, now fixed by #4164.

    Reproduction and regression status

    An independent standalone console program, outside the provider checkout, reproduced the report against an isolated PostgreSQL 18.4 instance on macOS arm64, with connection timezone UTC:

    Npgsql EF provider EF Core .NET runtime a.b database count a[^x]b database count
    10.0.4 10.0.15 10.0.8 0 0
    11.0.0 11.0.0 11.0.0 0 0
    main, built from 287351de397dc2889eb45ac0e0fc6e7250671c14 11.0.0 11.0.0 0 0
    8.0.8, historical comparison 8.0.8 8.0.31 0 0

    For the same input "a\nb", .NET returns false for a.b, but true for a[^x]b. Capturing a[^x]b in a variable instead of using a literal also returned database count 0 on all four versions.

    Thus this is not newly introduced in 10.0 or 11.0: it already reproduces on 8.0.8. No tested version worked; the original introduction and a last-known-good version were not established. PostgreSQL 18.6 and the reporter's .NET 10 runtime patch were not available, so those exact patches were not retested.

    The released 10.0.4, 11.0.0 and main executions generated:

    SELECT count(*)::int
    FROM "Rows" AS r
    WHERE r."Text" ~ '(?p)a.b'
    
    SELECT count(*)::int
    FROM "Rows" AS r
    WHERE r."Text" ~ '(?p)a[^x]b'

    With a captured pattern:

    -- @pattern = 'a[^x]b'
    SELECT count(*)::int
    FROM "Rows" AS r
    WHERE r."Text" ~ ('(?p)' || @pattern)

    Cause and other-provider comparison

    Current SQL generation uses p to keep dot from matching newline. PostgreSQL documents that this option also excludes newline from complemented bracket expressions. .NET instead defines dot and negative character groups separately.

    Direct PostgreSQL execution confirmed:

    PostgreSQL option a.b matches "a\nb" a[^x]b matches "a\nb" Anchors are line-sensitive
    p false false no
    n false false yes
    s true true no
    w true true yes

    There is no equivalent flag for .NET's default dot/bracket combination. Multiline without Singleline has the same bracket mismatch under n; fixing the combined Singleline | Multiline case does not fix this case.

    SQLite/EF Core 11.0 executed the exact two-argument queries and returned counts 0 for dot and 1 for the negative bracket, including a parameterized pattern. Its regex function calls .NET's implementation. This is therefore a PostgreSQL-provider semantic mismatch, not a demonstrated upstream EF query-pipeline defect.

    No matching existing provider/upstream duplicate or fix was found in targeted searches. #4094 now concerns replacement syntax; #4155/#4164 concern combined options. #2585 changed SQL construction, not this semantic distinction. dotnet/efcore#22497 introduced SQLite translation, not a fix for this issue.

    Fix feasibility

    There are possible partial improvements, but no general flag-only correction:

    • For a tightly restricted, dot-free constant pattern without inline options, omitting p would fix this example without a parser. However, an equivalent captured parameter would still behave differently, and mixed dot/bracket patterns remain wrong. Whether a literal-only improvement is worthwhile is an explicit compatibility/scope decision, not a complete solution.
    • Rewriting actual wildcard dots to [^\n] and using s (w with multiline anchors) can handle ordinary patterns. A lexical scanner is needed, not string.Replace: direct probes showed that naive replacement changes working a\.b and a[.]b into nonmatching patterns. Escaped-backslash parity, bracket boundaries, POSIX bracket constructs, and comments/expanded syntax must be distinguished. .NET inline option scopes also change which dots need rewriting; PostgreSQL only supports embedded options at the start, not .NET's scoped/mid-pattern forms. These are existing dialect restrictions, not features a narrow improvement necessarily needs to implement, but rewriting must not silently reinterpret them.
    • Alternatively, keeping p and rewriting a negative bracket into a grouped newline alternative can work. It must preserve quantifiers and avoid introducing capturing groups. It must not add newline when the original class excludes it through \n, \s, \u000A, or a range: direct probes confirmed these classes should remain nonmatching. A lookahead-based reformulation can avoid computing class membership, but still needs correct class boundaries and produces more complex regexes.
    • Constants are available during SQL translation; parameter values are not. Consistent parameter support would require additional runtime parameter processing; database-derived patterns would need server-side processing or a deliberately unsupported case. Client preprocessing adds work at translation/binding; server preprocessing of column patterns adds per-row work. No performance benchmark was performed. Globally switching to s would instead change existing wildcard-dot matches, while switching anchor modes would change line behavior.

    This would be a best-effort dialect adapter, not exact .NET parity. Even after a dot rewrite, other differences remain: for example, the direct probe Regex.IsMatch("a\n", "^a$") is true in .NET but false under PostgreSQL p or s, because of trailing-newline anchor treatment.

    Given the existing dynamic-pattern support and the narrow scope of this issue, documenting is preferable to a transparent constant-only rewrite or new runtime machinery.

    Practical workarounds and suggested documentation

    For the reported pattern, this preserves default dot/anchor settings and worked on all four provider executions:

    Regex.IsMatch(r.Text, @"a(?:[^x]|\n)b")

    This is an application-owned adjustment for a class known to allow newline, not an instruction to add newline to every negative class.

    For application-owned patterns, another approach is RegexOptions.Singleline with actual wildcard dots explicitly written as [^\n]. The probes confirmed both a[^x]b matching newline and a[^\n]b excluding it under that option. Singleline alone is not a general workaround, because it also changes ordinary dots. For exact .NET semantics, explicitly evaluate Regex on the client after suitable server-side narrowing, accepting the additional data transfer.

    Suggested note beside the regex entries/on the introduction of the translations page, whose source is npgsql/doc's conceptual/EFCore.PG/mapping/translations.md:

    Regex translations execute PostgreSQL's regular-expression engine, not .NET's. Patterns must use PostgreSQL-compatible syntax, and RegexOptions mapping does not guarantee identical semantics. With default options, or Multiline without Singleline, negated brackets such as [^x] do not match \n, unlike .NET. PostgreSQL has no flag preserving both .NET's default dot and negated-bracket newline behavior. Adapt the pattern explicitly or evaluate on the client when exact .NET behavior is required.

    This is a longstanding limitation, so the conceptual translation documentation is the appropriate location, not a new-version fix note. No implementation, documentation edit, or closure is proposed as already performed.

    minimal repro

    Use Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0 in a net11.0 console project. Set Test__Npgsql__DefaultConnection to a disposable PostgreSQL database: this program deletes and recreates it. The following compact program was also independently compiled and executed.

    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    using System.Text.RegularExpressions;
    
    await using var context = new TestContext();
    await context.Database.EnsureDeletedAsync();
    await context.Database.EnsureCreatedAsync();
    context.Rows.Add(new Row { Text = "a\nb" });
    await context.SaveChangesAsync();
    var row = await context.Rows.AsNoTracking().SingleAsync();
    
    Console.WriteLine($"dot: .NET {Regex.IsMatch(row.Text, "a.b")}, database {await context.Rows.CountAsync(r => Regex.IsMatch(r.Text, "a.b"))}");
    Console.WriteLine($"bracket: .NET {Regex.IsMatch(row.Text, "a[^x]b")}, database {await context.Rows.CountAsync(r => Regex.IsMatch(r.Text, "a[^x]b"))}");
    
    public class TestContext : DbContext
    {
        public DbSet<Row> Rows => Set<Row>();
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"))
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    }
    
    public class Row
    {
        public int Id { get; set; }
        public string Text { get; set; } = "";
    }

    Output:

    dot: .NET False, database 0
    bracket: .NET True, database 0
    
  2. added theissue type on Nov 25, 2026
  3. roji commented on Nov 25, 2026

    @roji
    Member

    Closing as not planned. This is a longstanding difference between PostgreSQL and .NET regular-expression semantics, which we will document rather than add automatic pattern rewriting.

    PostgreSQL uses the p/n modes to prevent . from matching LF, but those modes also prevent negated character classes such as [^x] from matching LF. In .NET, a default-mode dot excludes LF while [^x] includes it. No PostgreSQL flag provides that combination; changing flags globally would fix this example but change existing wildcard-dot behavior.

    A pattern rewrite could improve some cases, but would require parsing escapes, character classes and options correctly, and handling constant, parameterized and database-derived patterns consistently. That would introduce substantial complexity and additional processing for only partial .NET compatibility, since other dialect differences would remain. A constant-only rewrite would also make equivalent literal and parameterized patterns behave differently. We do not consider those tradeoffs worthwhile for this issue.

    The limitation and the supported options/overloads are documented in npgsql/doc#485, currently open. For this particular application-owned pattern, a(?:[^x]|\n)b explicitly allows LF without changing dot behavior; this is not a general rewrite for arbitrary negated classes. Use explicit client-side evaluation when exact .NET regex semantics are required.

  4. removed theissue type on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions