【问题标题】:Find all indexes for a specified string within a string in C#在 C# 中的字符串中查找指定字符串的所有索引
【发布时间】:2012-06-12 06:34:19
【问题描述】:

您好,我正在尝试使用来自

的解决方案

Find all pattern indexes in string in C#

但是,在我的情况下它不起作用

string sentence = "A || ((B && C) || E && F ) && D || G";
string pattern = "(";
IList<int> indeces = new List<int>();
foreach (Match match in Regex.Matches(sentence, pattern))
{
  indeces.Add(match.Index);
}

它会产生错误,“解析”(“ - 不够)”。

我不确定我在这里做错了什么。

感谢任何帮助。

谢谢,

巴兰辛尼亚

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    我不确定我在这里做错了什么。

    您忘记了( 在正则表达式中具有特殊含义。如果你使用

    string pattern = @"\(";
    

    我相信它应该可以工作。或者,继续使用string.IndexOf,因为您并没有真正使用正则表达式的模式匹配。

    如果您打算使用正则表达式,我会亲自创建一个Regex 对象而不是使用静态方法:

    Regex pattern = new Regex(Regex.Escape("("));
    foreach (Match match in pattern.Matches(sentence))
    ...
    

    这样一来,关于哪个参数是输入文本,哪个是模式,混淆的范围就比较小了。

    【讨论】:

      【解决方案2】:

      在这方面使用正则表达式是多余的 - IndexOf 就足够了。

      string sentence = "A || ((B && C) || E && F ) && D || G";
      string pattern = "(";
      IList<int> indeces = new List<int>();
      int index = -1;
      while (-1 != (index = sentence.IndexOf('(', index+1)))
      {
        indeces.Add(index);
      }
      

      或者,在你的情况下,你需要转义(,因为它是正则表达式的特殊字符,所以模式是"\\("

      编辑:修复,谢谢科比

      【讨论】:

      • Op 想要 all 索引,但您必须多次调用 IndexOf,不是吗?
      • @dbaseman,是的,当然。但我很确定它会比使用 Regex 更快。
      • 如果您希望程序停止,您可能需要while (-1 != (index = sentence.IndexOf('(', index + 1)))。在那之前,正则表达式肯定更快:)
      【解决方案3】:

      你必须转义(

      换句话说:

      string pattern = "\\(";
      

      【讨论】:

      • 或者你也可以在字符串之前的 at 这样你就不必转义反斜杠@"\("
      猜你喜欢
      • 2012-05-29
      • 2021-09-09
      • 2013-11-04
      • 2012-05-19
      • 2012-11-15
      • 2016-02-15
      • 1970-01-01
      相关资源
      最近更新 更多