C#中如何正确拆分含单引号包裹项的字符串?
解决字符串拆分问题的两种方案
方案1:基于现有Split方法调整
你选的分隔符','是对的,问题出在拆分后首尾元素的单引号不完整。只需要先清理字符串收尾的多余字符,再补全每个元素的单引号即可:
string str = "'Item Name:Item ID','Item name with, comma:Some ID','Some Name:Some ID';"; // 先去掉末尾的分号 str = str.TrimEnd(';'); // 用指定分隔符拆分 string[] separator = { "','" }; string[] strlist = str.Split(separator, StringSplitOptions.RemoveEmptyEntries); // 补全每个元素的单引号 for (int i = 0; i < strlist.Length; i++) { if (i == 0) { strlist[i] = strlist[i] + "'"; } else if (i == strlist.Length - 1) { strlist[i] = "'" + strlist[i]; } else { strlist[i] = "'" + strlist[i] + "'"; } Console.WriteLine(strlist[i]); }
运行后输出:
'Item Name:Item ID' 'Item name with, comma:Some ID' 'Some Name:Some ID'
如果不需要保留单引号,直接去掉补全引号的逻辑即可。
方案2:正则表达式(更健壮)
如果用户输入格式稳定为'内容','内容';结构,用正则匹配单引号内的内容会更可靠,能兼容更多边界情况:
using System.Text.RegularExpressions; string str = "'Item Name:Item ID','Item name with, comma:Some ID','Some Name:Some ID';"; // 匹配所有单引号包裹的内容,[^']*表示匹配除单引号外的任意字符 MatchCollection matches = Regex.Matches(str, @"'([^']*)'"); foreach (Match match in matches) { // 带单引号输出 Console.WriteLine($"'{match.Groups[1].Value}'"); // 不带单引号直接输出:Console.WriteLine(match.Groups[1].Value); }
这个方法不受字符串内部逗号或其他特殊字符影响,完美适配你“除引号外不限制用户输入”的需求。
内容的提问来源于stack exchange,提问作者icecub
相关产品推荐
相关产品推荐

