Regex corresponds to the first file in the rar archive file file.

How should I do it? I saw a solution not using one regex for ruby ​​becaase ruby ​​does not support loookaround statements. But is this possible in C #?

[Test]
public void RarArchiveFirstFileNameShouldMatch() {
    var regex = new Regex(@"\.(rar|001)$", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    Assert.That(regex.IsMatch("filename.001"));
    Assert.That(regex.IsMatch("filename.rar"));
    Assert.That(regex.IsMatch("filename.part1.rar"));
    Assert.That(regex.IsMatch("filename.part01.rar"));
    Assert.That(regex.IsMatch("filenamepart44.rar"));
    Assert.That(regex.IsMatch("filename.004"), Is.False);
    Assert.That(regex.IsMatch("filename.057"), Is.False);
    Assert.That(regex.IsMatch("filename.r67"), Is.False);
    Assert.That(regex.IsMatch("filename.s89"), Is.False);
    Assert.That(regex.IsMatch("filename.part2.rar"), Is.False);
    Assert.That(regex.IsMatch("filename.part04.rar"), Is.False);
    Assert.That(regex.IsMatch("filename.part11.rar"), Is.False);
}
+3
source share
2 answers

This should pass your tests:

    var regex = new Regex(@"(\.001|\.part0*1\.rar|^((?!part\d*\.rar$).)*\.rar)$", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    Assert.That(regex.IsMatch("filename.001"));
    Assert.That(regex.IsMatch("filename.rar"));
    Assert.That(regex.IsMatch("filename.part1.rar"));
    Assert.That(regex.IsMatch("filename.part01.rar"));
    Assert.That(regex.IsMatch("filename.004"), Is.False);
    Assert.That(regex.IsMatch("filename.057"), Is.False);
    Assert.That(regex.IsMatch("filename.r67"), Is.False);
    Assert.That(regex.IsMatch("filename.s89"), Is.False);
    Assert.That(regex.IsMatch("filename.part2.rar"), Is.False);
    Assert.That(regex.IsMatch("filename.part04.rar"), Is.False);
    Assert.That(regex.IsMatch("filename.part11.rar"), Is.False);
+5
source

You can do this in one regex, in both C # and Ruby, but why bother?

You have not exactly determined what you want - you must first document this. Once you have registered it, it's easy to turn this description into regular code. I think this is more readable and most important:

/// <summary>
/// Returns true if a filename extension is .001.
/// If the extensions is .rar, check to see if there is a part number
/// immediately before the extension.
/// If there is no part number, return true.
/// If there is a part number, returns true if the part number is 1.
/// In all other cases, return false.
/// </summary>
static bool isMainFile(string name)
{
    string extension = Path.GetExtension(name);
    if (extension == ".001")
        return true;
    if (extension != ".rar")
        return false;
    Match match = Regex.Match(name, @"\.part(\d+)\.rar$");
    if (!match.Success)
        return true;
    string partNumber = match.Groups[1].Value.TrimStart('0');
    return partNumber == "1";
}

, , Path . , , , .

, , , - .

+2

Source: https://habr.com/ru/post/1731673/


All Articles