匹配字符串与通配符

时间:2016-08-23 15:44:34

标签: c# switch-statement

我有以下代码:

$count = 0;
foreach ($this->topics()->withCount('replies')->get() as $topic) {
    $count += $topic->replies_count;
}

问题是现在第二种情况不起作用。

我需要一些可以充当通配符的东西,以便任何" OR.ISSUE1234567"可以识别并赋予p变量适当的值。

所以如果d以" OR开头。" p的值将是"重新发行"。

关于如何做到这一点的任何想法?

4 个答案:

答案 0 :(得分:1)

似乎RegEx是一种更好的方法。使用RegEx,您可以使用通配符,它​​可以非常强大。如果你使用System.Text.RegularExpressions添加""你将能够访问它。以下是一个示例。您可以在Google上找到许多可以解释不同符号以及如何构建匹配模式的网站。

        string d = "OR.ISSUE226568";
        string p;

        if (Regex.IsMatch(d, "^OR.*$"))
        {
            Console.WriteLine("Worked!");
        }

        Console.ReadLine();

答案 1 :(得分:0)

您可以通过切换到使用条件而不是switch语句来执行此操作:

if (d == "VOID") 
{
    p = "VOID";
}
else if (d.StartsWith("OR."))
{
    p = "Reissue";
}

或者你可以看一下使用正则表达式来匹配你的字符串,如果你想做一些更复杂的事情(参见MSDN)。

答案 2 :(得分:0)

无法将switch块与通配符(或例如正则表达式)一起使用。但根据你的问题,你可以这样做:

string d = "OR.ISSUE226568";
if(d.StartsWith("OR."))
    d = d.Remove(3);
string p;
switch (d)
{
   case "VOID":
     p = "VOID";                        
     break;

   case "OR.":
     p = "Reissue";
     break;

   // other cases...
}

但由于您只有两个case语句,因此根本不需要switch。使用if/else更容易,也更有意义。

答案 3 :(得分:0)

如果您只有类型的检查开头支持,并且您可能需要在运行时更改它们,您可以使用字典:

string d = "OR.ISSUE226568";
//string d= "VOID";
// Dictionary with start of the string
var target = new Dictionary<string,string>() {
  {"VOID","Void"},
  {"OR.", "Reissue"}
};

// find the one that matches
var p = (from kv in target
        where d.StartsWith(kv.Key)
        select kv.Value).FirstOrDefault();
相关问题