如何按任意字符+指定字符分割字符串?C#技术咨询
解决方案:按“任意字符+指定字符”分割字符串并提取单词
.NET 的 String.Split 方法仅支持固定字符串/字符作为分隔符,不支持通配符或正则模式匹配,所以你没法用某个符号替代代码里的 * 实现忽略任意字符的分割。要实现需求,得用正则表达式来处理,下面是两种可行的实现方式:
方式一:用 Regex.Split 分割字符串
通过正则表达式匹配“任意空白+数字+点号+任意空白”的分隔模式,再分割字符串并过滤空项:
using System; using System.Text.RegularExpressions; class Program { static void Main() { string content = " 1. word 2. otherword 3. anotherword"; // 正则模式:\s* 匹配任意空白,\d+ 匹配1个以上数字,\. 匹配点号,\s* 匹配后续任意空白 string[] split = Regex.Split(content, @"\s*\d+\.\s*", StringSplitOptions.RemoveEmptyEntries); foreach (var word in split) { Console.WriteLine(word); } } }
执行后得到结果:{"word", "otherword", "anotherword"}
方式二:用 Regex.Matches 直接提取目标单词
既然核心需求是提取单词,直接用正则匹配目标内容更直观,无需分割:
using System; using System.Text.RegularExpressions; using System.Linq; class Program { static void Main() { string content = " 1. word 2. otherword 3. anotherword"; // 正则模式:(?<=\.\s) 正向后断言(匹配“点号+空白”之后的位置),\S+ 匹配非空白字符(即单词) var matches = Regex.Matches(content, @"(?<=\.\s)\S+"); string[] words = matches.Cast<Match>().Select(m => m.Value).ToArray(); foreach (var word in words) { Console.WriteLine(word); } } }
这种方式直接定位到单词位置,结果和方式一一致。
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

