---
title: "Keep the longest overlapping token match in C#"
url: https://recursiveai.org/onenlp/cookbook/keep-longest-overlapping-token-match/
description: "Resolve overlapping NLP token matches in C# with OneNLP. Keep the longest range per rule key, break ties by position, and keep separate hits."
version: "1.0.0"
---

# Keep the longest overlapping token match in C#

**OneNLP** is a free, open-source natural language processing library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneNlp) · [GitHub](https://github.com/recursive-ai-oss/onenlp-csharp) · [Docs](https://recursiveai.org/onenlp/docs/) · [Download example (.zip)](https://recursiveai.org/onenlp/cookbook/keep-longest-overlapping-token-match/keep-longest-overlapping-token-match.zip)

Use `GreedyMode.Longest` when two matches share tokens and you want the longer one.

```shell
dotnet add package RecursiveAI.OneNlp
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneNlp;
using RecursiveAI.OneNlp.Matching;

var doc = Pipeline.Blank()
    .Process("New York City Hall");
var matcher = new Matcher();
matcher.AddJson("PLACE", """
    [
      [{"LOWER":"new"},{"LOWER":"york"}],
      [{"LOWER":"york"},{"LOWER":"city"},
       {"LOWER":"hall","OP":"?"}]
    ]
    """, GreedyMode.Longest);
foreach (var hit in matcher.MatchSpans(doc))
    Console.WriteLine(hit.Text);
```

The snippet prints:

```text
York City Hall
```

Unzip [the example](https://recursiveai.org/onenlp/cookbook/keep-longest-overlapping-token-match/keep-longest-overlapping-token-match.zip), then `dotnet run`.

In this [token-pattern JSON](https://recursiveai.org/onenlp/docs/matching/#token-patterns), `"OP":"?"` makes `hall` optional; the full program uses the fluent `Pattern` API instead.

## Full program

```csharp
using RecursiveAI.OneNlp;
using RecursiveAI.OneNlp.Matching;

var doc = Pipeline.Blank().Process(
    "New York City Hall; New York");
var matcher = new Matcher();
matcher.Add("PLACE", [
    Pattern.Lower("new")
        .Then(Pattern.Lower("york")),
    Pattern.Lower("york")
        .Then(Pattern.Lower("city"))
        .Then(Pattern.Lower("hall"))
], GreedyMode.Longest);
foreach (var span in matcher.MatchSpans(doc))
    Console.WriteLine(span.Text);
```

`dotnet run` prints:

```text
York City Hall
New York
```

Here “New York” and “York City Hall” share a token in the first half of the input, so the three-token match wins. The second “New York” shares no tokens with it and survives. If nothing matches, `MatchSpans` returns an empty list.

## Variations

**Prefer the earliest start.** In the full program, replace `GreedyMode.Longest` with `GreedyMode.First`:

```csharp
], GreedyMode.First);
```

```text
New York
New York
```

## Related recipes

- [Match text token patterns](https://recursiveai.org/onenlp/cookbook/match-token-patterns/)
- [Match phrases](https://recursiveai.org/onenlp/cookbook/match-phrases/)

## The short answer

Register your overlapping patterns under one `Matcher` key with `GreedyMode.Longest`. OneNLP prefers more tokens, then an earlier start when the token counts tie. It drops any candidate that shares a token with one it has already kept for that key. You get non-overlapping matches for that key, not just the single longest hit in the document.

## How do I prevent overlapping token matches from being extracted twice?

First decide which patterns compete. In the full program, both alternatives go under `PLACE` because they describe the same kind of hit and shouldn’t claim the same token. If you register one under `CITY` and the other under `BUILDING`, both can survive: the greedy filter works on each key separately. Keep separate keys when overlaps are meaningful, not when you expect one key’s match to suppress another’s. If two patterns under one key find the exact same range, the matcher reports that range once even without greedy filtering.

Think in token ranges, not character ranges. Two intervals overlap when they cover at least one of the same tokens. Two hits that touch at a boundary can both survive. The standalone “New York” in the full program illustrates the other important case: a shorter hit isn’t discarded just for being shorter. It’s discarded only if it overlaps a hit that was kept.

## Does the longest token match have to start first?

No. The full program’s longer match starts at “York,” after the shorter match starts at “New.” `Longest` takes “York City Hall” anyway. Use `First` when the position matters more, such as when the first token marks the beginning of the field you’re extracting. `First` still prefers the longer match when two candidates start at the same token.

Greedy selection is not the order of the returned list. The [matching rules](https://recursiveai.org/onenlp/docs/matching/#several-patterns-keys-greedy-filtering-callbacks) order surviving hits by end token, then by start token, then by key registration order. If your input contains a short hit early and a long hit later, don’t assume the first returned span is the longest.
