在C#中拆分字符串时保留(并关联)分隔符

本文关键字:关联 分隔符 保留 拆分 字符串 | 更新日期: 2023-09-27 18:20:03

在拆分字符串时,我希望生成一系列标记-分隔符对。因此,使用,;作为我的分隔符,我希望" a , b;"生成new int[][]{{" a ",","},{" b",";"},{"",""}}。最后一个条目表示字符串以分隔符结尾。当然,两个连续的分隔符要用一个空标记来分隔。

在C#中拆分字符串时保留(并关联)分隔符

String.SplitRegex.Split都不允许这样的关联-结果总是字符串序列。即使在捕获序列中的拆分标记时,分隔符也会混合在一起。

然而,使用Regex.Matches(或Match/NextMatch)可以轻松完成此任务。诀窍是使用'G锚点(请参见正则表达式中的锚点),使匹配是增量的,并从上一个匹配恢复。

var input = @" a , b;whatever";
// The 'G anchor ensures the next match begins where the last ended.
// Then non-greedily (as in don't eat the separators) try to find a value.
// Finally match a separator.
var matches = Regex.Matches(input, @"'G(.*?)([,;])")
    .OfType<Match>();
// All the matches, deal with pairs as appropriate - here I simply group
// them into strings, but build a List of Pairs or whatnot.
var res = matches
    .Select(m => "{" + m.Groups[1].Value + "|" + m.Groups[2].Value + "}");
// res -> Enumerable with "{ a |,}", "{ b|;}" 
String trailing;
var lastMatch = matches.LastOrDefault();
if (lastMatch != null) {
    trailing = input.Substring(lastMatch.Index + lastMatch.Length);
    // If the separator was at the end, trailing is an empty string
} else {
    // No matches, the entire input is trailing.
    trailing = input;
}
// trailing -> "whatever"

根据需要填写详细信息(并解决任何问题)。为了保持整洁,请根据需要修改此代码,并将其放入方法中。