查找带有令牌的参数(IndexOf或IndexOfAny)

本文关键字:IndexOf IndexOfAny 参数 令牌 查找 | 更新日期: 2023-09-27 18:12:10

目前,我能够在下面提供的令牌中获得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方法来完成这个任务吗?我不知道该怎么做。程序工作正常,直到我发现这是给我的测试的可能结果

查找带有令牌的参数(IndexOf或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);

查找两个不需要索引操作和(昂贵的)字符串操作的匹配项。