Is there a built-in mechanism in .NET to match patterns other than Regular Expressions? I'd like to match using UNIX style (glob) wildcards (* = any number of any character).
I'd like to use this for a end-user facing control. I fear that permitting all RegEx capabilities will be very confusing.
Based on previous posts, I threw together a C# class:
Using it would go something like this:
The matching is NOT the same as the System.IO.Directory.GetFiles() method, so don't use them together.
I found the actual code for you:
I like my code a little more semantic, so I wrote this extension method:
(change the namespace and/or copy the extension method to your own string extensions class)
Using this extension, you can write statements like this:
Just sugar to make your code a little more legible :-)
If you use VB.Net, you can use the Like statement, which has Glob like syntax.
http://www.getdotnetcode.com/gdncstore/free/Articles/Intoduction%20to%20the%20VB%20NET%20Like%20Operator.htm
If you want to avoid regular expressions this is a basic glob implementation:
Use it like this:
The 2- and 3-argument variants of the listing methods like
GetFiles()
andEnumerateDirectories()
take a search string as their second argument that supports filename globbing, with both*
and?
.would yield
The docs state that there are some caveats with matching extensions. It also states that 8.3 file names are matched (which may be generated automatically behind the scenes), which can result in "duplicate" matches in given some patterns.
The methods that support this are
GetFiles()
,GetDirectories()
, andGetFileSystemEntries()
. TheEnumerate
variants also support this.