C#中按空格分割字符串并提取年份与科目变量的方法
两种字符串格式的分割方案(C#)
针对你遇到的两种字符串格式(带$包裹科目或直接空格分隔),这里提供两种实用的实现方式:
方法一:正则表达式(推荐,适配所有情况)
正则可以一次性匹配出年份和科目,无需复杂的字符串拼接:
using System.Text.RegularExpressions; string input = "12 $Math A Level$"; // 或 "12 Math A Level" var match = Regex.Match(input, @"^(\d+)\s+(?:\$(.*)\$|(.*))$"); if (match.Success) { string year = match.Groups[1].Value; string subject = string.IsNullOrEmpty(match.Groups[2].Value) ? match.Groups[3].Value : match.Groups[2].Value; // 输出结果:year=12,subject=Math A Level }
正则说明:
^(\d+):匹配开头的数字作为年份\s+:匹配年份后的空格(?:\$(.*)\$|(.*)):非捕获分组,要么匹配带$包裹的内容(分组2),要么匹配直接的科目文本(分组3)
方法二:基础字符串处理(无依赖,易理解)
如果不想用正则,也可以通过字符串索引直接处理:
string input = "12 $Math A Level$"; int firstSpaceIndex = input.IndexOf(' '); string year = input.Substring(0, firstSpaceIndex).Trim(); string subjectPart = input.Substring(firstSpaceIndex + 1).Trim(); // 处理$包裹的情况 string subject = subjectPart.StartsWith("$") && subjectPart.EndsWith("$") ? subjectPart.Substring(1, subjectPart.Length - 2) : subjectPart; // 结果同样是year=12,subject=Math A Level
你原来Split方法的后续处理(供参考)
如果坚持用Split,需要把年份后的所有元素拼接,再处理$:
char[] whitespace = new char[] { ' ', '\t' }; var parts = input.Split(whitespace, StringSplitOptions.RemoveEmptyEntries); string year = parts[0]; string subjectPart = string.Join(" ", parts.Skip(1)); string subject = subjectPart.StartsWith("$") && subjectPart.EndsWith("$") ? subjectPart.Substring(1, subjectPart.Length - 2) : subjectPart;
这种方法需要处理空条目(比如多个空格或制表符),还要拼接数组元素,不如前两种高效。
内容的提问来源于stack exchange,提问作者user2332
相关产品推荐
相关产品推荐

