【问题标题】:Keep (and associate) delimiters when splitting a string in C# [closed]在 C# 中拆分字符串时保留(和关联)分隔符 [关闭]
【发布时间】:2025-12-12 20:55:02
【问题描述】:

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

【问题讨论】:

  • 很抱歉,不清楚您在问什么
  • int[][]???我在那里看到了字符串...
  • 我看到“我想要”(两次!),但我没有看到代码或特定问题。

标签: c# split


【解决方案1】:

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

但是,使用Regex.Matches(或 Match/NextMatch)可以轻松完成此任务。诀窍是使用\G 锚点(请参阅Anchors in Regular Expressions),以便匹配是增量的并从上一个匹配中恢复。

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"

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

【讨论】:

  • 我明白我没有直接提问。问题是,“string.split 是否提供了一种从分隔字符串中检索分隔符的方法。”我希望我可以避免使用 indexOf 和正则表达式。