我想在一些分隔符上拆分一个字符串,并获取原始字符串中返回字符串的索引。就像MatchCollection
返回的Regex.Matches
一样。
类似
MatchCollection col = Regex.Split(text, @"[\.\-]");
我可以传递给Regex.Matches
的哪种模式会在我的分界符上返回MatchCollection
分割?
答案 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