【问题标题】:Split string and get start index of returned results拆分字符串并获取返回结果的起始索引
【发布时间】:2013-12-01 18:33:01
【问题描述】:

我想在一些分隔符上分割一个字符串,并在原始字符串中获取返回字符串的索引。就像Regex.Matches 返回的MatchCollection

类似

MatchCollection col = Regex.Split(text, @"[\.\-]");

我可以将什么模式传递给 Regex.Matches 以返回 MatchCollection 沿我的分隔符拆分?

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    您可以像往常一样使用正则表达式,并分组捕获文本。在这里,我们将每个组命名为part,并使用\.\- 作为这些部分的分隔符:

    string text = "hi.there-how-are.you";
    MatchCollection col = Regex.Matches(text,
        @"((?<part>[^\.\-]+)(\.\-))*(?<part>[^\.\-]+)");
    foreach (Match match in col) {
        var part = match.Groups["part"];
        Console.WriteLine(part.Value + " at " + part.Index);
    }
    

    所以基本上(&lt;part&gt;&lt;delimiter&gt;)*&lt;part&gt;。输出:

    hi at 0
    there at 3
    how at 9
    are at 13
    you at 17
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2019-06-13
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多