Reputation: 71
I have written this code using LINQ query
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);
}
}
it's output is something like this {Index=0, Value= {, Token=Brace}
But I want Output be like { BRACE
Upvotes: 0
Views: 50
Reputation: 7830
One possibility would be to modify the anonymous object - create the string from the Key
(=Brace) and the Value
(={ or }):
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);
}
The output is as desired:
{ BRACE
} BRACE
Upvotes: 1