【发布时间】:2013-12-01 18:33:01
【问题描述】:
我想在一些分隔符上分割一个字符串,并在原始字符串中获取返回字符串的索引。就像Regex.Matches 返回的MatchCollection。
类似
MatchCollection col = Regex.Split(text, @"[\.\-]");
我可以将什么模式传递给 Regex.Matches 以返回 MatchCollection 沿我的分隔符拆分?
【问题讨论】:
我想在一些分隔符上分割一个字符串,并在原始字符串中获取返回字符串的索引。就像Regex.Matches 返回的MatchCollection。
类似
MatchCollection col = Regex.Split(text, @"[\.\-]");
我可以将什么模式传递给 Regex.Matches 以返回 MatchCollection 沿我的分隔符拆分?
【问题讨论】:
您可以像往常一样使用正则表达式,并分组捕获文本。在这里,我们将每个组命名为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
【讨论】: