【问题标题】:check if a string has specified structure in C#检查字符串是否在 C# 中具有指定的结构
【发布时间】:2015-11-03 09:06:28
【问题描述】:

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

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

如何在 C# 中做到这一点?

【问题讨论】:

  • 请注意,如果{0} == H'e'l'l'o...
  • 怎么样?请帮我这样做:)
  • 尝试做一些基础研究,有很多关于正则表达式的信息,只需搜索即可。
  • “我的结构之一”...如果没有所有必需的信息,就不可能做出完整的答案。 SO 不是在这里为您工作,而是帮助解决现有 问题。请展示您已经尝试和研究过的解决问题的方法(以及没有奏效的方法以及为什么没有奏效)

标签: c# string


【解决方案1】:

如果你真的想用 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.");

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

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

从我所做的一些小基准测试中,我注意到".*?" 可能比".*" 快一点(你更改str.Replace)...

【讨论】:

    猜你喜欢
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    相关资源
    最近更新 更多