C# 使用标记(IndexOf或IndexOfAny)查找参数

C# 使用标记(IndexOf或IndexOfAny)查找参数,c#,xml,xpath,indexing,token,C#,Xml,Xpath,Indexing,Token,目前,我能够在我提供的令牌中获得xpath的值,如下所示 using (StreamReader streamReader = new StreamReader(memoryStream)) { while ((CurrentLine = streamReader.ReadLine()) != null) { int startPos = CurrentLine.IndexOf("{:"); int endPos = CurrentLine.Last

目前,我能够在我提供的令牌中获得xpath的值,如下所示

using (StreamReader streamReader = new StreamReader(memoryStream))
{
    while ((CurrentLine = streamReader.ReadLine()) != null)
    {
        int startPos = CurrentLine.IndexOf("{:");
       int endPos = CurrentLine.LastIndexOf(":}");

       if (startPos > 0 && endPos > 0)
       {
           string xPathstr = CurrentLine.Substring(startPos + 2, (endPos - startPos - 2));

           XPathNodeIterator myXPathNodeIterator = myXPathNavigator.Select("/"+ xPathstr);

           while (myXPathNodeIterator.MoveNext())
           {
               Console.WriteLine(myXPathNodeIterator.Current.Value);
               TemplateMemoryBuilder.Append(CurrentLine.Replace(CurrentLine.Substring(startPos, ((endPos + 2) - startPos)), myXPathNodeIterator.Current.Value));
               TemplateMemoryBuilder.Append(Environment.NewLine);
           }

       }
       else
       {
           TemplateMemoryBuilder.Append(CurrentLine);
           TemplateMemoryBuilder.Append(Environment.NewLine);
       }
    }
}
如果在一行中发现多个标记,我试图找到一种方法来获取带有标记的参数,例如:

This is a test to merge item {:/MyTest/TestTwo/Text1:} and {:/MyTest/TestTwo/Text2:} on the same line.

我可以使用IndexOfAny方法来完成这项任务吗?我不知道该怎么做。这个程序运行得很好,直到我发现这是给我的一个测试的可能结果。

您可以使用正则表达式来匹配您的令牌。这将使您的代码更具可读性

示例正则表达式和匹配代码

        var regex = new Regex("{:.+?}");
        var input =
            "This is a test to merge item {:/MyTest/TestTwo/Text1:} and {:/MyTest/TestTwo/Text2:} on the same line.";
        var matches = regex.Matches(input);

查找两个不带索引操作和(代价高昂的)字符串操作的匹配项

这会起作用,但这条路线会起作用吗?因为我从一个模板文件中读取这些标记,这些标记位于我的文档中,而不是直接输入?您正在逐行读取,以便可以将字符串输入regexhow我会根据上述代码将字符串输入RegEx吗?