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

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:

/// <summary>
/// Check if a given file is an archive of an original file.
/// The check is performed on the names of the files only.
/// </summary>
/// <param name="originalFile">The original file.</param>
/// <param name="archivedFile">The file which is supposed to be an archive of the original one.</param>
/// <returns>True if the file is an archive, False otherwise.</returns>
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;
}

• I'm sorry, I can't make the code formatting to work properly.
– Pierre 303
Feb 4 '11 at 19:04
• Do you need those wildcards to be those date formats, or could they be anything, e.g. serverw3BACKUP.log? Feb 4 '11 at 19:57
• Anything, this could replace the function
– Pierre 303
Feb 4 '11 at 20:29

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.

Here is the wildcard alternative

public bool IsArchive(string filePattern, string archivedFile)
{
return new Regex(filePattern.Replace("*", "[^ ]*")).IsMatch(archivedFile);
}