2016-03-25 49 views
0

我一直在使用LINQ查詢寫了這個代碼打印輸出我如何以某種方式

static public void BracesRule(String input) 
    { 
     //Regex for Braces 
     string BracesRegex = @"\{|\}"; 

     Dictionary<string, string> dictionaryofBraces = new Dictionary<string, string>() 
     { 
      //{"String", StringRegex}, 
      //{"Integer", IntegerRegex }, 
      //{"Comment", CommentRegex}, 
      //{"Keyword", KeywordRegex}, 
      //{"Datatype", DataTypeRegex }, 
      //{"Not included in language", WordRegex }, 
      //{"Identifier", IdentifierRegex }, 
      //{"Parenthesis", ParenthesisRegex }, 
      {"Brace", BracesRegex }, 
      //{"Square Bracket", ArrayBracketRegex }, 
      //{"Puncuation Mark", PuncuationRegex }, 
      //{"Relational Expression", RelationalExpressionRegex }, 
      //{"Arithmetic Operator", ArthimeticOperatorRegex }, 
      //{"Whitespace", WhitespaceRegex } 
     }; 
     var matches = dictionaryofBraces.SelectMany(a => Regex.Matches(input, a.Value) 
     .Cast<Match>() 
     .Select(b => 
       new 
       { 
        Index = b.Index, 
        Value = b.Value, 
        Token = a.Key 
       })) 
     .OrderBy(a => a.Index).ToList(); 

     for (int i = 0; i < matches.Count; i++) 
     { 
      if (i + 1 < matches.Count) 
      { 
       int firstEndPos = (matches[i].Index + matches[i].Value.Length); 
       if (firstEndPos > matches[(i + 1)].Index) 
       { 
        matches.RemoveAt(i + 1); 
        i--; 
       } 
      } 
     } 
     foreach (var match in matches) 
     { 
      Console.WriteLine(match); 
     } 

    } 

它的輸出是這樣的 {指數= 0,值= {,令牌=佈雷斯}

但我想輸出像 {BRACE

+0

你能否詳細說明更多littble位上的問題了嗎?你能提供一個你的輸入的例子嗎?你想要改變哪一部分(以及如何改變)?輸出? – pasty

+0

這是一個標記器。詞法分析器 輸入:{} 輸出:{指數= 0,值= {,令牌=底架} {指數= 1,值=},令牌=底架} 但我想輸出像 輸出:{底架 } Brace – Ali

+0

這是你的代碼,但你不能改變輸出格式? – pasty

回答

1

一種可能性是修改匿名對象 - 創建從Key(=大括號)字符串和Value(= {}或):

string input = "ali{}"; 
//Regex for Braces 
string BracesRegex = @"\{|\}"; 

Dictionary<string, string> dictionaryofBraces = new Dictionary<string, string>() 
{ 
    {"Brace", BracesRegex } 
}; 
var matches = dictionaryofBraces.SelectMany(a => Regex.Matches(input, a.Value) 
      .Cast<Match>() 
      .Select(b => String.Format("{0} {1}", b.Value, a.Key.ToUpper()))) 
      .OrderBy(a => a).ToList(); 

foreach (var match in matches) 
{ 
    Console.WriteLine(match); 
} 

輸出是期望:

{ BRACE 
} BRACE 
+0

工作伴侶。謝謝 – Ali

+0

很高興答案幫助。 – pasty