-
慕村225694
您可以使用以下行将其拆分为使用多个字符作为分隔符的数组,因为您的字符串值是使用逗号后跟空格分隔的,如您的示例所示。String[] strValues = strValue.Split(new string[] { ", " }, StringSplitOptions.None);这是一个DotNetFiddle编辑 - 鉴于需求的突然变化......如果你不关心结果的顺序,并且你想提取句子,因为它们都再次('N<sentence>')采用相同的格式,我们可以使用这样的东西来快速提取值:String strValue = "city, image, N'Hello, World , It Rain', picture";// Match the sentences by N'{text}'var strValues = Regex.Match(strValue, "(?<=N')(.*?)(?=')");// Remove the sentences from the stringforeach(var matchedVal in strValues.Captures){ var toRepl = String.Format("N'{0}', ", matchedVal.ToString()); strValue = strValue.Replace(toRepl, "");}// Split the remainder of the stringList<string> strOtherValues = strValue.Split(new string[] { ", " }, StringSplitOptions.None).ToList();// Add all sentences to words listforeach (var matchedVal in strValues.Captures){ strOtherValues.Add(matchedVal.ToString());}
-
子衿沉夜
嗯,这是一个完美的烂摊子;可能也有糟糕的表现。但至少它似乎可以做你想做的事(还没有测试过很多极端情况)。问题是,您需要以某种方式区分“内部”或“外部”原始字符串的“转义”部分。如果您在“内部”,则不应通过分隔符进行正常拆分。public static IEnumerable<string> MySpecialSplit(string value, string separator, string escapeStart, string escapeEnd){ var result = new List<string>(); var start = value.StartsWith(separator) ? separator.Length : 0; var inEscape = false; for (var i = start; i < value.Length - separator.Length; i++) { if (inEscape && value.Length > i + escapeEnd.Length && value.Substring(i, escapeEnd.Length).Equals(escapeEnd)) { inEscape = false; } else if (!inEscape && value.Length > i + escapeStart.Length && value.Substring(i, escapeStart.Length).Equals(escapeStart)) { inEscape = true; } if (!inEscape && value.Substring(i, separator.Length).Equals(separator)) { result.Add(value.Substring(start, i - start)); i += separator.Length; start = i; i--; } } if (start < value.Length - separator.Length) { var rest = value.Substring(start); if (rest.EndsWith(separator)) { rest = rest.Substring(0, rest.Length - separator.Length); } result.Add(rest); } return result;}像这样使用它:var splitted = MySpecialSplit("city, image, N'Hello, World , It's Rain', picture", ", ", "N'", "',");Console.WriteLine(string.Join(Environment.NewLine, splitted));结果:cityimageN'Hello, World , It's Rain'picture
-
德玛西亚99
似乎您的字符串格式已知有 4 个字段逗号分隔,在这种情况下使用正则表达式知道第三个字段可能有逗号: String strValue = "city, image, N'Hello, World , It Rain', picture"; Pattern PATTERN = Pattern.compile("([^,]+), ([^,]+), (.+), ([^,]+)"); Matcher matcher = PATTERN.matcher(strValue); if (matcher.find()) { System.out.println(matcher.group(1)); System.out.println(matcher.group(2)); System.out.println(matcher.group(3)); System.out.println(matcher.group(4)); }