【问题标题】:How do I print output in a certain way如何以某种方式打印输出
【发布时间】:2016-07-13 05:10:12
【问题描述】:

我使用 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}

但我希望输出像 { 大括号

【问题讨论】:

  • 您能否详细说明您的问题?你能提供一个你输入的例子吗?您究竟想要更改哪一部分(以及如何更改)?输出?
  • 这是一个分词器。词法分析器输入:{} 输出:{Index=0, Value= {, Token=Brace} {Index=1, Value= }, Token=Brace} 但我希望输出类似于输出:{ Brace } Brace
  • 这是您的代码,但您不能更改输出格式?
  • 我已经尝试了很多。我还在学习 LINQ 查询。所以没有太多投入!对不起!可以使用帮助!

标签: c# linq token cc


【解决方案1】:

一种可能性是修改匿名对象 - 从 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 

【讨论】:

  • 很高兴这个答案有帮助。
猜你喜欢
  • 1970-01-01
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多