public string[] StringToArray(string input) { var pattern = new Regex(@" \[ (?: \s* (?(?: (?(open) [^\[\]]+ | [^\[\],]+ ) |(?\[) |(?<-open>\]) )+) (?(open)(?!)) ,? )* \] ", RegexOptions.IgnorePatternWhitespace); // Find the first match: var result = pattern.Match(input); if (result.Success) { // Extract the captured values: var captures = result.Groups["results"].Captures.Cast().Select(c => c.Value).ToArray(); return captures; } // Not a match return null; }
var pattern = new Regex(@" \[ (?: \s* (?(?: # Capture everything into 'results' (?(open) # If 'open' Then [^\[\]]+ # Capture everything but brackets | # Else (not open): (?: # Capture either: [^\[\],'""]+ # Unimportant characters | # Or ['""][^'""]*?['""] # Anything between quotes ) ) # End If |(?\[) # Open bracket |(?<-open>\]) # Close bracket )+) (?(open)(?!)) # Fail while there's an unbalanced 'open' ,? )* \] ", RegexOptions.IgnorePatternWhitespace);
使用Regex,它可以解决您的问题:
static string[] StringToArray(string str) { Regex reg = new Regex(@"^\[(.*)\]$"); Match match = reg.Match(str); if (!match.Success) return null; str = match.Groups[1].Value; List list = new List(); reg = new Regex(@"\[[^\[\]]*(((?'Open'\[)[^\[\]]*)+((?'-Open'\])[^\[\]]*)+)*(?(Open)(?!))\]"); Dictionary dic = new Dictionary(); int index = 0; str = reg.Replace(str, m => { string temp = "ojlovecd" + (index++).ToString(); dic.Add(temp, m.Value); return temp; }); string[] result = str.Split(','); for (int i = 0; i < result.Length; i++) { string s = result[i].Trim(); if (dic.ContainsKey(s)) result[i] = dic[s].Trim(); else result[i] = s; } return result; }
private static IEnumerable StringToArray1(string input) { Stack> levelEntries = new Stack>(); List current = null; StringBuilder currentLineBuilder = new StringBuilder(); foreach (char nextChar in input) { switch (nextChar) { case '[': levelEntries.Push(current); current = new List(); break; case ']': current.Add(currentLineBuilder.ToString()); currentLineBuilder.Clear(); var last = current; if (levelEntries.Peek() != null) { current = levelEntries.Pop(); current.Add(last); } break; case ',': current.Add(currentLineBuilder.ToString()); currentLineBuilder.Clear(); break; default: currentLineBuilder.Append(nextChar); break; } } return current; }
无论什么味道对你有好处
using System; using System.Text; using System.Text.RegularExpressions; using Microsoft.VisualBasic.FileIO; //Microsoft.VisualBasic.dll using System.IO; public class Sample { static void Main(){ string data = "[a, b, [c, [d, e]], f, [g, h], i]"; string[] fields = StringToArray(data); //check print foreach(var item in fields){ Console.WriteLine("\"{0}\"",item); } } static string[] StringToArray(string data){ string[] fields = null; Regex innerPat = new Regex(@"\[\s*(.+)\s*\]"); string innerStr = innerPat.Matches(data)[0].Groups[1].Value; StringBuilder wk = new StringBuilder(); var balance = 0; for(var i = 0;i