HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

How to reduce this archive detection function and make it supports wildcards

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thiswildcardsmakefunctionsupportsreducedetectionhowandarchive

Problem

The function below is called to determine if a given file is the archive of another file. I'm also looking for a way to supports wildcards. For example if the original log file is serverw3c.log and we type serverw3c*.log, it returns true for the following:

  • serverw3c.log.2011-02-04



  • serverw3c.log



  • serverw3c.log.20110204_120132



  • serverw3c_20110204.log



The code:

/// 
/// Check if a given file is an archive of an original file.
/// The check is performed on the names of the files only.
/// 
/// The original file.
/// The file which is supposed to be an archive of the original one.
/// True if the file is an archive, False otherwise.
public bool IsArchive(string originalFile, string archivedFile)
{
    // We assume that an archived file has the name of the original 
    // concatenated with a timestamp '.YYYYMMDD_HHMMSS'
    Regex exp = new Regex(string.Concat(originalFile, ".", "[0-9][0-9][0-9][0-9][0-1][0-9][0-9][0-9]_[0-2][0-9][0-5][0-9][0-5][0-9]"));
    if (exp.IsMatch(archivedFile))
        return true;

    exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile), "_", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]", Path.GetExtension(".log")));
    if (exp.IsMatch(archivedFile))
        return true;

    exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile), "_", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]", "_", "[0-9][0-9][0-9]", Path.GetExtension(".log")));
    if (exp.IsMatch(archivedFile))
        return true;

    exp = new Regex(string.Concat(originalFile, ".", "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]"));
    if (exp.IsMatch(archivedFile))
        return true;

    return false;
}

Solution

Your regex can be shortened using {x}, which repeat a pattern x times. So your third regex would become:

exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile),
                              "_[0-9]{8}_[0-9]{3}",
                              Path.GetExtension(".log")));


As far as wildcards, if you use * it will be entered into the regex. It looks from MSDN that it won't be removed from the file name when you call GetFileNameWithoutExtension(). However, I was unable to test this as I don't have Visual Studio on my computer. It worked as a wildcard on my regex tests.

Code Snippets

exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile),
                              "_[0-9]{8}_[0-9]{3}",
                              Path.GetExtension(".log")));

Context

StackExchange Code Review Q#611, answer score: 4

Revisions (0)

No revisions yet.