我需要使用 c# regex 拆分输入字符串。需要知道如何在输出中包含分隔符内容,如下所示。
输入:
string content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";
string[] delimters = new string[] {"heading1:","heading2:","heading3:"};
预期输出:
outputArray[0] = heading1: contents with respect to heading1
outputArray[1] = heading2: heading2 contents
outputArray[2] = heading3: heading 3 related contents sample strings
我试过的:
var result = content.Split(delimters,StringSplitOptions.RemoveEmptyEntries);
我得到的输出:
result [0]: " contents with respect to heading1 "
result [1]: " heading2 contents "
result [2]: " heading 3 related contents sample strings"
我无法在 string.split 或 Regex 中找到 API 来拆分为预期结果。
您可以使用基于正向预测的解决方案:
var result = Regex.Split(content, $@"(?={string.Join("|", delimiters.Select(m => Regex.Escape(m)))})")
.Where(x => !string.IsNullOrEmpty(x))
请参阅C# 演示:
var content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";
var delimiters = new string[] {"heading1:","heading2:","heading3:"};
Console.WriteLine(
string.Join("\n",
Regex.Split(content, $@"(?={string.Join("|", delimiters.Select(m => Regex.Escape(m)))})")
.Where(x => !string.IsNullOrEmpty(x))
)
);
输出:
heading1: contents with respect to heading1
heading2: heading2 contents
heading3: heading 3 related contents sample strings
该(?={string.Join("|", delimiters.Select(m => Regex.Escape(m)))})
会动态地构造一个正则表达式,它看起来像
(?=heading1:|heading2:|heading3:)
请参阅正则表达式演示。该模式将基本上匹配字符串中的任何位置herring1:
,herring2:
或者herring3:
不消耗这些子字符串,因此它们将出现在输出中。
请注意,这delimiters.Select(m => Regex.Escape(m))
是为了确保可能在分隔符中的所有特殊正则表达式元字符都被正则表达式引擎转义并视为文字字符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句