【问题标题】:Finding the parameters with tokens (IndexOf or IndexOfAny)使用标记(IndexOf 或 IndexOfAny)查找参数
【发布时间】:2011-10-24 20:23:22
【问题描述】:

目前,我能够在我提供的令牌中获取 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 方法来完成这项任务吗?我不知道该怎么做。程序运行良好,直到我发现这是给我的测试的可能结果

【问题讨论】:

    标签: c# xml xpath indexing token


    【解决方案1】:

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

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

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

    找到两个没有索引操作和(昂贵的)字符串操作的匹配项。

    【讨论】:

    • 这可行,但由于我是从模板文件中读取这些令牌位于我的文档中而不是直接输入的,因此这条路线是否可行?
    • 您正在逐行阅读,因此您可以将字符串输入到正则表达式中
    • 如何根据上面的代码将字符串输入到 RegEx 中?
    猜你喜欢
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多