2013-01-07 2 views
0

복잡한 문자열을 Tree 데이터 구조로 구문 분석하는 가장 쉬운 방법을 이해하는 데 도움이 필요합니다. C#을 사용하여이 문자열을 구문 분석 할 수있는 방법을 파악하려고합니다. |복잡한 문자열을 데이터 구조로 구문 분석하는 방법

[[Le[[filet|tartare]]|La grillade]]de gateau|Une [[portion|part]] de gateau 

[...] 집합이며 : 여기

이 문자열의 예 예를 들어, 그때 드 gateau``올 어떻게

Set 1 
     Set 1-1 
      Le 
      Set 1-1-1 
       filet 
       tartare 
      La grillade 
    Set 2 
     Une 
     Set 2-1 
      portion 
      part 
     de gateau 
+1

가 세트 2에서오고, 몇명'후 얻을 필요가

세트의 구분은 ...' ? – nhahtdh

+1

http://en.wikipedia.org/wiki/Finite-state_machine –

+0

@nhahtdh - 최상위 레벨 집합의 두 번째 상위 수준 구분 기호 뒤에 있습니다. – Oded

답변

0
using System; 
using System.Collections.Generic; 
using System.IO; 

class Tree 
{ 
    int currentIndent; 

    public Tree(string s) 
    { 
     this.Trees = new List<Tree>(); 
     this.Values = new List<string>(); 
     this.currentIndent = 0; 

     if (s == null) 
      throw new ArgumentNullException(); 

     if (s == "") 
      return; 

     int beginPos = 0; 
     while (beginPos < s.Length) 
     { 
      if (s[beginPos] == '[') 
      { 
       string res = ""; 
       uint openedBraceCount = 1; 
       uint closedBraceCount = 0; 
       int index = beginPos + 1; 
       while (openedBraceCount != closedBraceCount) 
       { 
        if (s[index] == '[') 
         openedBraceCount++; 
        if (s[index] == ']') 
         closedBraceCount++; 
        res += s[index]; 
        index++; 
       } 
       beginPos = index; 
       this.Trees.Add(new Tree(res.Substring(0, res.Length - 1))); 
      } 
      else 
      { 
       int endPos = beginPos + 1; 
       while (endPos < s.Length && s[endPos] != '[') 
        endPos++; 
       string[] values = s.Substring(beginPos, endPos - beginPos).Split('|'); 
       for (int i = 0; i < values.Length; i++) 
        values[i] = values[i].Trim(); 
       this.Values.AddRange(values); 
       beginPos = endPos; 
      } 
     } 
    } 

    public void Print(TextWriter writer, int indent) 
    { 
     this.currentIndent = indent; 
     Print(writer, 0, this); 
     this.currentIndent = 0; 
    } 

    private void Print(TextWriter writer, int indent, Tree tree) 
    { 
     foreach (string value in tree.Values) 
      writer.WriteLine("{0}{1}", new string(' ', indent), value); 
     foreach (Tree t in tree.Trees) 
      Print(writer, currentIndent + indent, t); 
    } 

    public List<Tree> Trees { get; set; } 

    public List<string> Values { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     string s = "[[Le[[filet|tartare]]|La grillade]]de gateau|Une [[portion|part]] de gateau"; 
     var tree = new Tree(s); 
     tree.Print(Console.Out, 2); 
    } 
} 
관련 문제