如何使用Regex.Split实现保留部分分隔符、排除部分分隔符?
解决方案
推荐用正则匹配提取的方式实现,比单纯用Regex.Split更直接贴合需求,具体实现如下:
正则表达式
(week.*?)(?=\snext\s)|(?<=\snext\s)(.*?if)
C# 代码示例
string input = "This week rained all day long but next day will be a sunny day if the news are correct"; // 匹配目标片段 MatchCollection matches = Regex.Matches(input, @"(week.*?)(?=\snext\s)|(?<=\snext\s)(.*?if)"); // 输出结果 foreach (Match match in matches) { Console.WriteLine(match.Value); }
输出结果
week rained all day long but day will be a sunny day if
正则逻辑解释
(week.*?)(?=\snext\s):匹配从week起始,到next(前后带空格)之前的所有内容,正向预查(?=\snext\s)确保不会把next包含到结果里(?<=\snext\s)(.*?if):匹配从next之后开始,到if结束的所有内容,反向预查(?<=\snext\s)确保不会把next包含到结果里
如果一定要用Regex.Split实现,可以参考如下写法(相对繁琐):
string input = "This week rained all day long but next day will be a sunny day if the news are correct"; // 用This、next、if后面的内容作为分割符 string[] parts = Regex.Split(input, @"(?:This\s)|(?:\snext\s)|(?:if\s.*)"); // 过滤空元素,给第二个片段补上if List<string> result = new List<string>(); if (!string.IsNullOrEmpty(parts[1])) result.Add(parts[1]); if (!string.IsNullOrEmpty(parts[2])) result.Add($"{parts[2]}if"); // 输出结果 foreach (string part in result) { Console.WriteLine(part); }
内容的提问来源于stack exchange,提问作者user20465780
相关产品推荐
相关产品推荐

