Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中的字符串中查找指定字符串的所有索引#_C#_Regex - Fatal编程技术网

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

C# 在C中的字符串中查找指定字符串的所有索引#,c#,regex,C#,Regex,嗨,我正在尝试使用来自的解决方案 然而,在我的情况下,它不起作用 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)) {

嗨,我正在尝试使用来自的解决方案

然而,在我的情况下,它不起作用

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);
}
string-station=“A | | |((B&C)| | E&F)和&D | | G”;
字符串模式=“(”;
IList indeces=新列表();
foreach(正则表达式中的Match.Matches(句子、模式))
{
添加(匹配索引);
}
它会产生错误,“解析”(“-不够)”

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

谢谢你的帮助

谢谢


Balan Sinniah

在这个问题上使用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);
}
string-station=“A | | |((B&C)| | E&F)和&D | | G”;
字符串模式=“(”;
IList indeces=新列表();
int指数=-1;
而(-1!=(索引=句子.IndexOf(“(”,索引+1)))
{
增加(索引);
}
或者,在您的例子中,您需要转义
),因为它是正则表达式的特殊字符,所以模式应该是
“\\”(“


编辑:修复,谢谢Kobi

您必须退出

换言之:

string pattern = "\\(";
我不确定我在这里做错了什么

您忘记了
在正则表达式中有一个特殊的含义

string pattern = @"\(";
我相信它应该会起作用。或者,只要继续使用
string.IndexOf
,因为您并没有真正使用正则表达式的模式匹配

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

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

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

Op想要所有的索引……你必须多次调用IndexOf,不是吗?@dbaseman,是的,当然。但我很确定这比使用正则表达式要快。你可能需要
while(-1!=(index=句子.IndexOf(“(”,index+1))
如果你想让你的程序永远停止。在那之前,正则表达式肯定要快些
:)
或者你也可以在字符串前面加一个at,这样你就不必转义反斜杠
@“\(“