Pattern matching filenames

S

Sea Sharper

Hi,

C#, from a FileSystemWatcher I would like to catch all files with a *.*
filter but then inside the event handler compare against a list of wildcards
(eg '*.abc;*.def')

Is there anywhere inside the Framework where I can do something like

Pattern x = new Pattern("*.abc");
if ( x.Matches(strFilename) )
{
//do something
}

Obviously I could just assume the file extensions were being used (and use
Path.GetExtension accordingly), but if a wildcard such as 'xyz??.*' is used
then I havent a hope.

Hope you can help, thanks

BTW:
The Regex syntax is different from filename
wildcards.

I could write a conversion from filename wildcard to regex syntax (eg. ? to
..?) but it would be fragile to change and possibly buggy.

Surely there must a simple way of doing this?

Thanks for the help

p.s. If you cannot help me then you force me to write new code of my own!!

Sea
 
C

Chris R. Timmons

Hi,

C#, from a FileSystemWatcher I would like to catch all files
with a *.* filter but then inside the event handler compare
against a list of wildcards (eg '*.abc;*.def')

Is there anywhere inside the Framework where I can do something
like

Pattern x = new Pattern("*.abc");
if ( x.Matches(strFilename) )
{
//do something
}

Obviously I could just assume the file extensions were being
used (and use Path.GetExtension accordingly), but if a wildcard
such as 'xyz??.*' is used then I havent a hope.

Hope you can help, thanks

BTW:
The Regex syntax is different from filename
wildcards.

I could write a conversion from filename wildcard to regex
syntax (eg. ? to .?) but it would be fragile to change and
possibly buggy.

Sea,

Why would converting to the regex syntax be buggy or fragile?

The DOS wildcard spec only has two metacharacters - * and ?. Those
are easy to replace. Here's how I would approach the problem:


1. Escape the input string.

string pattern = Regex.Escape("xyz??.*");

// pattern will now look like "xyz\?\?\.\*"


2. Replace all "\?" with .

pattern = pattern.Replace(@"\?", ".");

// pattern now looks like this: "xyz..\.\*"


3. Replace all "\*" with .*

pattern = pattern.Replace(@"\*", ".*");

// pattern now looks like this: "xyz..\..*"


If you want to completely violate the Law of Demeter, you could
combine all three steps like this:

string pattern = Regex.Escape("xyz??.*").Replace(@"\?",
".").Replace(@"\*", ".*");



Chris.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top