拆分字符串并获取返回结果的起始索引

时间:2013-12-01 18:33:01

标签: c# regex

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

类似

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

我可以传递给Regex.Matches的哪种模式会在我的分界符上返回MatchCollection分割?

1 个答案:

答案 0 :(得分:0)

您可以像往常一样使用正则表达式,并以组的形式捕获文本。在此,我们将每个组命名为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);
}

基本上(<part><delimiter>)*<part>。输出:

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