C#使用通配符

时间:2016-07-25 09:35:12

标签: c# validation compare version wildcard

让我们假设我有两个“版本”的东西。 一个是实际版本(例如1.5.2.1)

另一个是一个如下所示的字符串:1. *或1.5。*。

我想验证实际版本的通配符是否为真。

为了更好地理解:

Validation(1.5.2.1,1.*) should be true.
Validation(1.5.2.1,1.5.*) should also be true.
Validation(1.5.2.1,1.5.1.*) should be false.
Validation(2.5.0.0,1.*) should be false.
Validation(1.5,2.*) should also return true. // This Case breaks all of my attempts.
Validation for "*" only should always be true.

任何人都可以帮我吗?

2 个答案:

答案 0 :(得分:2)

您可以使用SplitZip来合并两个拆分结果并遍历这些项目:

string value = "1.5.2.1";
string pattern = "1.5.*";

var parts = value.Split('.').Zip(pattern.Split('.'), (valuePart, patternPart) => new { Value = valuePart, Pattern = patternPart });

bool result = true;

foreach (var part in parts)
{
    if (part.Pattern == "*")
    {
        result = true;
        break;
    }

    int p = Int32.Parse(part.Pattern);
    int v = Int32.Parse(part.Value);

    if (p < v)
    {
        result = false;
        break;
    }
    else if (p > v)
    {
        result = true;
        break;
    }
}

答案 1 :(得分:0)

针对更新的问题更新了答案:

public static bool Validation(Version installedVersion, string allowedVersions)
{
    var components = new [] {int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue};
    var split = allowedVersions.Split('.');

    for (int i = 0; i < split.Length; ++i)
        if (split[i] != "*")
            components[i] = int.Parse(split[i]);

    return installedVersion <= new Version(components[0], components[1], components[2], components[3]);
}

示例测试代码:

Console.WriteLine(Validation(new Version("1.5.2.1"), "1.*"));     // True
Console.WriteLine(Validation(new Version("1.5.2.1"), "1.5.*"));   // True
Console.WriteLine(Validation(new Version("1.5.2.1"), "1.5.1.*")); // False
Console.WriteLine(Validation(new Version("2.5.0.0"), "1.*"));     // False
Console.WriteLine(Validation(new Version("1.1.0.0"), "2.*"));     // True
Console.WriteLine(Validation(new Version("2.5.0.0"), "*"));       // True

[编辑:稍微简化代码]