• Stars
    star
    338
  • Rank 124,403 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 8 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A fast globbing library for .NET / .NETStandard applications. Outperforms Regex.

DotNet.Glob

A fast (probably the fastest) globbing library for .NET.

say thanks - if you'd like this library enough please consider giving back with a small donation.

Branch Build Status NuGet
Master Build master NuGet
Develop Build status NuGet

This library does not use Regex - I wanted to make something faster. The latest benchmarks show that DotNet.Glob outperforms Regex - that was my goal for this library. The benchmarks use BenchmarkDotNet and can be located inside this repo. Just dotnet run them. Some Benchmark results have also been published on the wiki: https://github.com/dazinator/DotNet.Glob/wiki/Benchmarks-(vs-Compiled-Regex)

Usage

  1. Install the NuGet package. Install-Package DotNet.Glob
  2. Add using statement: using DotNet.Globbing;
  3. Parse a glob from a pattern
 var glob = Glob.Parse("p?th/*a[bcd]b[e-g]a[1-4][!wxyz][!a-c][!1-3].*");
 var isMatch = glob.IsMatch("pAth/fooooacbfa2vd4.txt"); // You can also use ReadOnlySpan<char> on supported platforms.

Build a glob fluently

You can also use the GlobBuilder class if you wish to build up a glob using a fluent syntax. This is also more efficient as it avoids having to parse the glob from a string pattern.

So to build the following glob pattern: /foo?\\*[abc][!1-3].txt:

  var glob = new GlobBuilder()
                .PathSeparator()
                .Literal("foo")
                .AnyCharacter()
                .PathSeparator(PathSeparatorKind.BackwardSlash)
                .Wildcard()
                .OneOf('a', 'b', 'c')
                .NumberNotInRange('1', '3')
                .Literal(".txt")
                .ToGlob();

   var isMatch = glob.IsMatch(@"/fooa\\barrra4.txt"); // returns true.

Patterns

The following patterns are supported (from wikipedia):

Wildcard Description Example Matches Does not match
* matches any number of any characters including none Law* Law, Laws, or Lawyer
? matches any single character ?at Cat, cat, Bat or bat at
[abc] matches one character given in the bracket [CB]at Cat or Bat cat or bat
[a-z] matches one character from the range given in the bracket Letter[0-9] Letter0, Letter1, Letter2 up to Letter9 Letters, Letter or Letter10
[!abc] matches one character that is not given in the bracket [!C]at Bat, bat, or cat Cat
[!a-z] matches one character that is not from the range given in the bracket Letter[!3-5] Letter1, Letter2, Letter6 up to Letter9 and Letterx etc. Letter3, Letter4, Letter5 or Letterxx

In addition, DotNet Glob also supports:

Wildcard Description Example Matches Does not match
** matches any number of path / directory segments. When used must be the only contents of a segment. /**/some.* /foo/bar/bah/some.txt, /some.txt, or /foo/some.txt

Escaping special characters

Wrap special characters ?, *, [ in square brackets in order to escape them. You can also use negation when doing this.

Here are some examples:

Pattern Description Matches
/foo/bar[[].baz match a [ after bar /foo/bar[.baz
/foo/bar[!!].baz match any character except ! after bar /foo/bar7.baz
/foo/bar[!]].baz match any character except an ] after bar /foo/bar7.baz
/foo/bar[?].baz match an ? after bar /foo/bar?.baz
/foo/bar[*]].baz match either a * or a ] after bar /foo/bar*.baz,/foo/bar].baz
/foo/bar[*][]].baz match *] after bar /foo/bar*].baz

ReadOnlySpan

ReadOnlySpan<char> is supported as of version 3.0.0 of this library. You can read more about Span here: https://msdn.microsoft.com/en-us/magazine/mt814808.aspx

You must be targeting a platform that supports ReadOnlySpan<T> for this API to become available. These are currently:

  • .NET Core 2.1
  • Platforms that implement .NET Standard 2.1

Usage remains very similar, except you can use the overload that takes a ReadOnlySpan<char> as opposed to a string:

    var glob = Globbing.Glob.Parse("p?th/*a[bcd]b[e-g]a[1-4][!wxyz][!a-c][!1-3].*");
    var span = "pAth/fooooacbfa2vd4.txt".AsSpan();
    Assert.True(glob.IsMatch(span));

There should be some performance benefits in utilising this in conjunction with other Span based API's being added to the .net framework / .net standard.

Advanced Usages

Options.

DotNet.Glob allows you to set options at a global level, however you can also override these options on a per glob basis, by passing in your own GlobOptions instance to a glob.

To set global options, use GlobOptions.Default.

For example:

    // Overide the default options globally for all matche:
    GlobOptions.Default.Evaluation.CaseInsensitive = true;   
	DotNet.Globbing.Glob.Parse("foo").IsMatch("Foo"); // true; 

Or, override any global default options, by passing in your own instance of GlobOptions:

    GlobOptions options = new GlobOptions();
    options.Evaluation.CaseInsensitive = false;
    DotNet.Globbing.Glob.Parse("foo", options).IsMatch("Foo"); // false; 

Case Sensitivity (Available as of version >= 2.0.0)

By default, evaluation is case-sensitive unless you specify otherwise.

    GlobOptions options = new GlobOptions();
    options.Evaluation.CaseInsensitive = true;
    DotNet.Globbing.Glob.Parse("foo*", options).IsMatch("FOo"); // true; 

Setting CaseInsensitive has an impact on:

  • Letter Ranges. Any letter range (i.e '[A-Z]') will now match both lower or upper case characters.
  • Character Lists. Any character list (i.e '[ABC]') will now match both lower or upper case characters.
  • Literals. Any literal (i.e 'foo') will now match both lower or upper case characters i.e FoO will match foO etc.

Match Generation

Given a glob, you can generate random matches, or non matches, for that glob. For example, given the glob pattern /f?o/bar/**/*.txt you could generate matching strings like /foo/bar/ajawd/awdaw/adw-ad.txt or random non matching strings.

  var dotnetGlob = Glob.Parse(pattern);
  var generator = new GlobMatchStringGenerator(dotnetGlob.Tokens);

  for (int i = 0; i < 10; i++)
  {
          var testString = generator.GenerateRandomMatch();
          var result = dotnetGlob.IsMatch(testString);
          // result is always true.

          // generate a non match.
          testString = generator.GenerateRandomNonMatch();
          var result = dotnetGlob.IsMatch(testString);
           // result is always false.
  }

Give Back

If this library has helped you, even in a small way, please consider a small donation via https://opencollective.com/darrell-tunnell It really would be greatly appreciated.

More Repositories

1

Dotnettency

Mutlitenancy for dotnet applications
C#
106
star
2

AspNetCore.LegacyAuthCookieCompat

Provides classes to encrypt / decrypt asp.net 2 / 3.5 / 4 and 4.5 FormsAuthenticationTickets (cookies) without relying on system.web
C#
68
star
3

BlazorDeferredRemove

Create Blazor UI that can wait for CSS animations or transitions to complete before being removed from the DOM.
HTML
39
star
4

Dazinator.Extensions.DependencyInjection

Useful additions to Microsoft.Extensions.DependencyInjection such as Named Services.
C#
37
star
5

Dazinator.Extensions.FileProviders

C#
36
star
6

DnnPackager

Automate the packaging logic for your DotNetNuke projects, deploy to your IIS from within Visual Studio.
C#
20
star
7

BlazorPlugins

Dynamically load plugins into your blazor applications
C#
17
star
8

CrmUp

CrmUp helps you to deploy changes to Microsoft Dynamics Crm in a Continuos manner using a Migrations approach.
C#
14
star
9

NetPack

.Net Core library, for runtime processing of static files such as typescript, js, css etc.
JavaScript
13
star
10

DotNet.Cabinet

Cabinet, is a layered, virtual file system API for netstandard platforms.
C#
13
star
11

stint

A job runner for .net applications, extensible and configurable.
C#
10
star
12

NuGetFlow

a smooth and continuous process of downloading and integrating NuGet packages into an dotnet application.
C#
8
star
13

CrmSync

A .NET library that facilitates synchronisation (download only, or bi-directional) of entities between a Dynamics Crm server and an "offline" store / local database, allowing your application to remain operational even when Dynamics CRM is not available.
C#
8
star
14

CrmRequire

A .NET library that helps you easily check for required runtime dependencies on Dynamics CRM
C#
7
star
15

GithubReleaseCreator

A small and flexible command line utility, that can create releases on GitHub, including setting the release notes, and uploading file assets.
C#
7
star
16

CrmAdo

An ADO.NET Provider for Dynamics Crm
C#
6
star
17

Dotnettency.Samples

Samples for dotnettency - that demonstrate multi-tenancy and modular applications.
C#
6
star
18

CrmDeploy

A .Net Library to enable you to easily deploy components to Dynamics CRM such as registering plugins.
6
star
19

Dazinator.Extensions.WritableOptions

Writeable Options for asp.net core
C#
5
star
20

AspNetSolutionUpgradeTool

A utility that can be used to upgrade an ASP.NET 5 RC1 or RC2 based solution to ASP.NET Core 1.0.0 RTM.
C#
5
star
21

Dazinator.ResponsiveCore

Enable your .net applications to be more responsive to changes at runtime, so you don't have to restart the application in order for changes to take effect. It does this whilst trying to be as minimally invasive in your code base as possible.
C#
5
star
22

Changify

Small dotnet library making it easier to work with and build complex ChangeTokens
C#
4
star
23

Dazinator.Extensions.Options

Useful extensions to Microsoft.Extensions.Options
C#
4
star
24

Xamarin.TestyDroid

TestyDroid is a small command line tool, to handle running your unit tests on an android device during CI builds.
C#
4
star
25

Portable.System.Data.Common

A PCL compatible version of System.Data.Common
C#
3
star
26

Xamarin.Standard

Xamarin.Standard
C#
3
star
27

multistartup

Progressive Startup for your ASP.NET Core Applications
C#
2
star
28

Redesigner

Redesgner is a tool to generate and validate ASP.NET designer files
C#
2
star
29

AspNetCore-Identity-MultiDomain

An example trying to get asp.net core identity working with seperate domains
C#
2
star
30

Repros

Repro's for issues I encounter
C#
2
star
31

NetPack.Samples

TypeScript
2
star
32

CrmAdo.Ddex

A Visual Studio Extension that allows you to connect to Dynamics CRM 2011 & 2013 instances from Server Explorer. The technical visual studio term is "Data Designer Extensibility". See entities, attributes, plugins etc.
C#
2
star
33

Dazinator.Extensions.Options.Globbing

Extension for Microsoft.Extensions.Options that allows you to configure named options using glob patterns.
C#
2
star
34

MonoDroid.ViewLifecycleManager

Tracks activities so you can get the "current top" on MonoDroid.
1
star
35

MonoDroid.ActivityResult

Provides a mechnaism for results that are typically received by an xamarin android activity, to be intercepted by other components.
C#
1
star
36

PersonalBlog

HTML
1
star
37

CarbCycle

Idea for a food diary app specifically for Carb cycling.
1
star
38

Csla.Orleans

Host a Csla Server as an Orleans Grain.
C#
1
star
39

Dazinator.Extensions.Http

Adjust http client configuration at runtime - solved.
C#
1
star
40

Dazinator.AspNetCore.Authorization

Useful classes and extensions when working with Microsoft.Extensions.Authorization
C#
1
star
41

VisualStudio.CustomTool.AscxDesignerGenerator

A visual studio CPS extension, that can generate designer.cs files for ascx (webforms) files.
C#
1
star
42

Dazinator.Extensions.Options.ItemChanged

C#
1
star
43

Dazinate.Dnn

.Net libraries for "doing things" with DotNetNuke.
C#
1
star
44

GitHookExperiment

C#
1
star
45

DotNet.SourceMaps

A dotnet library to produce and consume sourcemaps.
C#
1
star
46

NuFridge

NuFridge is a web application for managing your NuGet feeds.
JavaScript
1
star
47

Dazinator.Extensions.Configuration

Make implementing an IConfigurationProvider even easier.
C#
1
star