Snowberry.Globbing
2.1.0
dotnet add package Snowberry.Globbing --version 2.1.0
NuGet\Install-Package Snowberry.Globbing -Version 2.1.0
<PackageReference Include="Snowberry.Globbing" Version="2.1.0" />
<PackageVersion Include="Snowberry.Globbing" Version="2.1.0" />
<PackageReference Include="Snowberry.Globbing" />
paket add Snowberry.Globbing --version 2.1.0
#r "nuget: Snowberry.Globbing, 2.1.0"
#:package Snowberry.Globbing@2.1.0
#addin nuget:?package=Snowberry.Globbing&version=2.1.0
#tool nuget:?package=Snowberry.Globbing&version=2.1.0
Snowberry.Globbing
Accurate glob pattern matching for .NET. Match paths and strings against glob patterns with wildcards, globstars, brace expansion, extended globs and POSIX character classes, with the matching semantics of the JavaScript library picomatch. Patterns compile to a regex that behaves identically in .NET, JavaScript and PostgreSQL 17+, so the same glob can filter files in memory, in a browser and in a database query.
Targets .NET 10 and .NET Standard 2.0. The .NET 10 build has no dependencies; the .NET Standard 2.0 build depends only on System.Memory.
Table of Contents
- Installation
- Quick Start
- Top Features at a Glance
- How It Works
- Pattern Syntax
- Options
- Using the Regex in JavaScript and PostgreSQL
- Error Handling
- Performance
- Pitfalls
Installation
dotnet add package Snowberry.Globbing
Quick Start
using Snowberry.Globbing;
// 1. One-off check: the static IsMatch caches compiled single patterns.
bool isSource = Glob.IsMatch("src/lib/app.cs", "src/**/*.cs"); // true
// 2. Compile once, match many: Glob is immutable and thread-safe.
var glob = new Glob("**/*.{cs,csproj}", new GlobOptions { IgnorePatterns = ["**/bin/**", "**/obj/**"] });
glob.IsMatch("src/App/App.csproj"); // true
glob.IsMatch("src/App/bin/Debug/App.cs"); // false (ignored)
// 3. Filter a sequence; results keep the input order.
string[] files = ["README.md", "src/Program.cs", "src/obj/Generated.cs"];
var sources = glob.Filter(files); // ["src/Program.cs"]
// 4. Get the regex for other engines.
string regex = new Glob("src/**/*.cs").ToRegexString();
Top Features at a Glance
One reusable type.
Globcompiles a pattern, or several patterns of which any may match, once. It offersIsMatch(string),IsMatch(ReadOnlySpan<char>),Match,Filter,ToRegexandToRegexString.Immutable options.
GlobOptionsis a record: share one instance across threads and derive variants withwith.IgnorePatternsis copied when set, so later changes to your list do not leak into the options.var options = GlobOptions.Default with { IgnoreCase = true, MatchDotFiles = true };Match details.
Matchreports whether an input was excluded by an ignore pattern and which pattern matched first.GlobMatch result = glob.Match("src/obj/Generated.cs"); // result.Success == false, result.IsIgnored == true, result.Pattern == "**/*.{cs,csproj}"Portable regex.
ToRegexString()returns one regex source for .NET, JavaScript and PostgreSQL, verified against picomatch by a cross-engine conformance suite.Pattern analysis.
Glob.Analyzesplits a pattern into its literal base directory and its glob part, which is what a directory walker needs.GlobInfo info = Glob.Analyze("src/lib/**/*.cs"); // info.BasePath == "src/lib", info.GlobPart == "**/*.cs", info.HasGlobstar == trueFast matching. Common shapes such as
*.js,**/*.csandsrc/**are matched with string operations, without a regex. For other patterns, literal text the pattern requires, such as the.tsofsrc/*/*.ts, is checked with ordinal string comparisons first, so most non-matching inputs never reach the regex engine.IsMatchon an existingGlobdoes not allocate on .NET 10 unlessInputNormalizeris set.
How It Works
A pattern is compiled once, when the Glob is created:
flowchart LR
pattern[Pattern] --> lexer[Lexer] --> tree[Syntax tree] --> emitter[Emitter] --> source[Portable regex source] --> regex[Regex]
tree --> literal["Required literal text<br/>(prefix, suffix, substring)"]
Matching then normalizes each input and runs the cheapest checks first:
flowchart TD
input[Input] --> normalize["Normalize separators<br/>(or InputNormalizer)"]
normalize --> equal{Input equals<br/>the pattern?}
equal -- yes --> ignored
equal -- no --> shape{Common shape?}
shape -- yes --> direct{"Matches, checked<br/>without a regex?"}
direct -- no --> noMatch([No match])
direct -- yes --> ignored
shape -- no --> hasLiteral{Required literal<br/>text present?}
hasLiteral -- no --> noMatch
hasLiteral -- yes --> regexMatch{Regex matches?}
regexMatch -- no --> noMatch
regexMatch -- yes --> ignored{Matches an<br/>ignore pattern?}
ignored -- yes --> noMatch
ignored -- no --> match([Match])
With several patterns, the checks before the ignore patterns run for each pattern in order, and the first one that matches wins. When a glob has many patterns, an index of required three-character substrings skips the patterns an input cannot match.
Common shapes such as *.js, **/*.cs, src/** and plain names are matched with string operations, without running a regex. Most chains of wildcards, such as *a*b*c, compile to regexes that do not backtrack between the wildcards. A negated pattern such as !**/node_modules/** is matched by testing its body and inverting the result, so the string-operation and literal checks apply there too. Only the regex source is public through ToRegexString(); the other steps are applied by Glob itself.
Pattern Syntax
| Syntax | Matches |
|---|---|
* |
Any characters in one path segment, except / |
? |
One character, except / |
** |
Any number of path segments |
[abc], [a-z], [!a] |
One character from, or not from, the set |
[[:alpha:]], [[:digit:]] |
A POSIX character class |
{a,b} |
Any of the alternatives |
{1..5}, {01..10}, {1..9..2}, {a..e} |
A numeric range, zero-padded or stepped, or a character range |
!pattern |
Anything that does not match pattern |
@(a\|b) |
Exactly one of the alternatives |
?(a\|b), *(a\|b), +(a\|b) |
Zero or one, zero or more, one or more of the alternatives |
!(a\|b) |
Anything except the alternatives |
\* |
A literal * (any character can be escaped) |
Wildcards do not match a leading . in a segment unless MatchDotFiles is set. An input that is exactly equal to the pattern always matches that pattern; ignore patterns still apply.
Options
| Option | Default | Description |
|---|---|---|
IgnoreCase |
false |
Match case-insensitively, using culture-invariant rules |
MatchDotFiles |
false |
Let wildcards match segments starting with . |
MatchFileNameOnly |
false |
Match only the file name of the input, ignoring directories |
MatchSubstring |
false |
Match anywhere in the input instead of the whole input |
PathStyle |
Auto |
Posix: only / separates, \ in inputs is an ordinary character; Windows: \ in inputs is converted to /; Auto: like Posix, but converts \ in inputs when running on Windows |
IgnorePatterns |
empty | Patterns that exclude otherwise matching inputs; compiled with the same options |
BraceExpansion |
true |
Expand {a,b} and {1..5} |
BracketExpressions |
true |
Support [abc] |
Extglobs |
true |
Support @(...), !(...) and the other extended globs |
Globstar |
true |
Let ** cross directories |
Negation |
true |
Treat a leading ! as negation |
PosixClasses |
true |
Expand [[:alpha:]] and the other POSIX classes |
StrictSlashes |
false |
Do not let trailing wildcards also match a trailing / |
StrictBrackets |
false |
Throw on unbalanced [, ( and { instead of matching them literally |
RegexOptions |
None |
Extra options for the regex used for matching and returned by ToRegex(), for example RegexOptions.Compiled; NonBacktracking is not supported |
MatchTimeout |
null |
Time limit for each regex evaluation; null uses the process-wide REGEX_DEFAULT_MATCH_TIMEOUT, Regex.InfiniteMatchTimeout disables it |
MaxPatternLength |
65536 |
Longest accepted pattern |
InputNormalizer |
null |
Transforms each input before matching, replacing the separator conversion of PathStyle |
Rarely needed compatibility switches: BracketMode, BashCompatibility, RegexQuantifiers, KeepQuotes, Unescape, CaptureGroups and BraceRangeExpander. See their XML documentation.
Using the Regex in JavaScript and PostgreSQL
ToRegexString() returns one regex source that matches the same inputs in .NET, JavaScript and PostgreSQL 17+, including inputs with line breaks. Use it without flags in JavaScript:
const isSource = new RegExp(source).test("src/lib/app.cs");
With Npgsql or EF Core, pass RegexOptions.Singleline. Without it, Npgsql adds PostgreSQL's (?p) flag, which stops * and ? from matching line breaks:
string source = new Glob("src/**/*.cs").ToRegexString();
var files = await db.Files.Where(f => Regex.IsMatch(f.Path, source, RegexOptions.Singleline)).ToListAsync();
The regex covers the patterns only. Glob applies the rest itself: IgnoreCase (use RegexOptions.IgnoreCase, ~* in PostgreSQL or the i flag in JavaScript), RegexOptions, MatchTimeout, IgnorePatterns, MatchFileNameOnly, input normalization and the input-equals-pattern rule.
PostgreSQL Performance
- A trigram index works. With
CREATE EXTENSION pg_trgmand agin (path gin_trgm_ops)index, the planner uses the index for any pattern with a literal word of two or more letters or digits, such as thecsof**/*.csor thenode_modulesof**/node_modules/**. The lookaheads in the regex do not prevent this. Patterns without such a literal (*,**,**/.*) and negated patterns (!*.md) still scan the table. - Keep combined regexes small. PostgreSQL builds the matching automaton again for every row, so the cost per row grows with the length of the regex. A
Globof 1,000 patterns gives a 60 KB regex that takes about 2 seconds to compile per connection and about 1 ms per row. For long pattern lists, narrow the rows first with a cheaper or indexed condition, such as aLIKEon a required extension, and apply the combined regex to the rest. - Use
~ ANY(...)for at most 32 regexes.path ~ ANY(@regexes), with oneToRegexString()per pattern, is faster than one combined regex while the array has at most 32 entries. PostgreSQL caches 32 compiled regexes per connection, so a longer array compiles every regex again for every row. - Prefer glibc-based images. On Alpine-based PostgreSQL images, regexes with more than about 20 distinct characters, such as
**/{yarn.lock,package-lock.json}, are 10 to 20 times slower per row than onpostgres:17, because musl's allocator is slow for the automaton's per-row allocations.
Error Handling
| Situation | Exception |
|---|---|
null pattern, pattern list or input |
ArgumentNullException |
| An empty pattern list | ArgumentException |
| Any invalid pattern or ignore pattern | GlobParseException, with an Error code |
A regex evaluation exceeds MatchTimeout, or the process-wide default when it is null |
RegexMatchTimeoutException |
Error |
Cause |
|---|---|
EmptyPattern |
The pattern, a pattern in the list or an ignore pattern is null or empty |
PatternTooLong |
The pattern is longer than MaxPatternLength |
MissingClosingBracket, MissingOpeningBracket, MissingClosingParenthesis, MissingOpeningParenthesis, MissingClosingBrace |
An unbalanced delimiter, with StrictBrackets |
NestingTooDeep |
Groups, braces or extended globs nested more than 256 levels deep |
InvalidPattern |
The pattern is not a valid regex, such as [z-a], or RegexOptions is an invalid combination or unsupported, such as NonBacktracking |
GlobParseException derives from ArgumentException and carries the Pattern, the Error code and the Offset; its ParamName names the argument the pattern came from (pattern, patterns or IgnorePatterns). Use Glob.TryCreate to validate user-supplied patterns without exceptions. Its error reports every failure, including a null pattern, as a GlobParseException, so you can switch on the code:
if (!Glob.TryCreate(userPattern, options, out var glob, out var error))
{
return error.Error switch
{
GlobParseError.EmptyPattern => Results.BadRequest("Enter a pattern."),
GlobParseError.PatternTooLong => Results.BadRequest("The pattern is too long."),
_ => Results.BadRequest($"Invalid pattern at position {error.Offset}: {error.Message}"),
};
}
Performance
- Reuse
Globinstances. Construction parses and compiles the pattern; matching does not. The staticGlob.IsMatch(input, pattern)caches compiled patterns, but a long-lived instance is cheaper still. - The pattern-list overload is not cached.
Glob.IsMatch(input, patterns)compiles all patterns on every call; create aGlobfrom the list instead. - Interpreted regex by default.
RegexOptions.Compiledpays a large one-time IL-generation cost (hundreds of microseconds to milliseconds per pattern). SetRegexOptions = RegexOptions.Compiledonly for a glob reused across tens of thousands of inputs or more. Patterns matched without a regex never build one, so the option only affects the others. - A match timeout has a small cost. With
MatchTimeoutset, the regex engine checks the clock while matching, which made patterns that run a regex up to about 20% slower in benchmarks. Patterns matched without a regex, and the defaultnull, add nothing. - Many patterns. A glob with dozens to thousands of patterns, such as a
.gitignore, is indexed when it is created, which makes matching 4 to 30 times faster at 24 to 1,000 patterns for a small extra construction cost. - No allocations. On .NET 10,
IsMatchallocates nothing, including with ignore patterns, file-name matching and Windows separators, unlessInputNormalizeris set.Matchallocates only the normalized input when separators are converted. On .NET Framework, theReadOnlySpan<char>overload avoids a string only when every pattern has a common shape.
Pitfalls
Autopath style depends on the platform. On Windows,src\app.csmatchessrc/*.cs; on Linux it does not. SetPathStyle = GlobPathStyle.PosixorWindowswhen results must not depend on the OS.- A backslash in a pattern is always an escape. Write patterns with
/, even for Windows paths;src\*.csmeanssrc*.cswith a literal*. - Npgsql needs
RegexOptions.Singleline. Without it, inputs that contain line breaks match differently in PostgreSQL than in .NET. ToRegexString()does not encode every option. Ignore patterns, file-name matching, case-insensitivity,RegexOptionsandMatchTimeoutare not part of the regex text; apply them on the consuming side. Regex syntax you write into a pattern, such as\d, andBraceRangeExpanderoutput are copied as-is and are only portable if they are portable themselves.- Untrusted patterns need a
MatchTimeout. Most chains of wildcards do not backtrack, but repeated extended globs with overlapping alternatives backtrack exponentially:+(a|aa)btakes about 5 seconds on a 40-character input, and each extra character makes it about 1.6 times slower. When users supply patterns, setMatchTimeoutand handleRegexMatchTimeoutException. The limit applies per regex evaluation, so a glob with several patterns or ignore patterns can take a multiple of it. RegexOptions.NonBacktrackingis not supported. The generated regexes use lookarounds, which the non-backtracking engine rejects, so nearly every pattern fails withInvalidPattern. UseMatchTimeoutto bound matching time instead.- Some characters are not portable. PostgreSQL counts a character outside the Basic Multilingual Plane, such as an emoji, as one character, while .NET and JavaScript count two, so
?and the boundaries of*differ for such input. WithIgnoreCase, a few characters fold differently: .NET 10 folds the Kelvin sign (U+212A) tokand .NET Framework and JavaScript do not, and PostgreSQL folds the long s (U+017F) tosand .NET and JavaScript do not. An escaped ASCII letter, such as\a, is regex syntax and means different things in each engine. - Negated patterns never match line breaks.
!*.mddoes not match an input that contains\n,\ror a Unicode line separator. - Unbalanced delimiters are literal.
a{bmatches the texta{b. SetStrictBracketsto reject such patterns instead. - Large ranges match literally. A numeric range with more than 4,096 values, such as
{1..100000}, is not expanded and matches only its own text.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- System.Memory (>= 4.6.3)
-
net10.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.