tags:

views:

32

answers:

3

I am trying to create a regex that will take all files that do not have a list of extensions. In particular, I am trying to filter out filenames that end in .csv

I have browsed around for an hour and been unable to figure this out. I am using .NET Regex.

+3  A: 

The following should do the trick. I just tested it with .net.

^.*\.(?!csv).*$

Be sure to include the IgnoreCase RegexOptions to make it case insensitive.

Jason Webb
Thanks a ton, this worked perfect! Out of curiosity, why doesn't it work without the .* at the end?
NickLarsen
The * operator says "include any number of X or none at all". In this case X is a "." so its any character. If you want to require an extension of some kind switch that "*" to a "+"
Jason Webb
A: 
        For Each r As String In _invalidFileExpressions
            If bValid Then
                bValid = Not Regex.IsMatch(FileName, r, RegexOptions.IgnoreCase)
            End If
        Next

r would be defined as .net regular expression, some samples:

        ".*\.csv" 
        ".*d\.txt" 
        "\d\d_\d{8}[dmysDMYS].txt" 
        ".*(batch).*\.txt"
        ".*(elvis).*\.txt"
        ".*(anal).*\.txt"
        ".*(monthlystats)\.txt"
        ".*(rx)\.txt"
        ".*(BAD|bad)\.txt"
        ".*(mm)\.txt"
        ".*(flu)\.txt"
David
+1  A: 

If you're using .Net 3.5 or higher, this non-regex solution should work:

var root = new DirectoryInfo(@"C:\");
var files = root.GetFiles();

var filteredFiles = files.Where(f => f.Extension != "csv");
Austin Salonen
This is a good example, but it is actually a list of file names in a text file with no usable split string.
NickLarsen