检查字符串是否在C#中指定了结构

时间:2015-08-11 08:24:27

标签: c# string

我有一个字符串数组,我想检查我的字符串是否有指定的结构。例如我的一个结构是这样的:

The value '{0}' is not valid for {1}.

我怎样才能在C#中做到这一点?

1 个答案:

答案 0 :(得分:0)

如果你真的想用Regex(我认为就像玩火),你可以......

public static Regex MakeRegex(string str)
{
    // We temporarily replace the {x} with \0
    str = string.Format(str, "\0", "\0", "\0", "\0", "\0", "\0", "\0", "\0", "\0", "\0");

    // Then we escape the regex, so that for example the . is changed
    // to \.
    str = Regex.Escape(str);

    // We replace the \0 we had added in the beginning with .*
    str = str.Replace("\0", ".*");

    // We add the ^ and $ to anchor the regex
    str = "^" + str + "$";

    // The regex is complete
    return new Regex(str);
}

然后

Regex rx = MakeRegex("The value '{0}' is not valid for {1}.");
bool ismatch = rx.IsMatch("The value '1' is not valid for Foo.");

请注意,我认为这不是一个好主意......但有些人喜欢玩火。

如果您想多次重复使用,请缓存使用rx构建的MakeRegex

从我做过的一些迷你基准测试中,我发现".*?"可能比".*"(你更改str.Replace)快一点......