簡體   English   中英

如何以某種方式打印輸出

[英]How do I print output in a certain way

我已經使用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);
        }

    }

它的輸出是這樣的{Index = 0,Value = {,Token = Brace}

但我希望輸出像{BRACE

一種可能性是修改匿名對象-從Key (= Brace)和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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM