在C#中查找字符串中指定字符串的所有索引

时间:2012-06-12 06:34:20

标签: c# regex

您好我正在尝试使用

中的解决方案

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);
}

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

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

感谢任何帮助。

谢谢,

Balan Sinniah

3 个答案:

答案 0 :(得分:7)

  

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

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

string pattern = @"\(";
我相信它应该有效。或者,只要你没有真正使用正则表达式的模式匹配,就继续使用string.IndexOf

如果 要使用正则表达式,我个人创建一个Regex对象而不是使用静态方法:

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

这样,混淆的范围就越小,哪个参数是输入文本,哪个是模式。

答案 1 :(得分:3)

在此使用Regexs是过度的 - 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);
}

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

编辑:修复,谢谢Kobi

答案 2 :(得分:2)

你必须逃避(

换句话说:

string pattern = "\\(";
相关问题