1

Story: I have a list box that shows all the methods of the current application. I need to colorize the method parameters' data type to blue.

Solution: FIRST, I extract the content between the parenthesis. SECOND, I want to split them by COMMA

Problem: If the arguments entail something like IDictionary<string, string> which occurs multiple times, then the above solution faces problem!! Thus, I decided to FIRST grab all the content between the angle brackets and then Replace their comma with "#COMMA#" and after performing the task using the above solution simply replace the "#COMMA#" with ",". BUT, based on the solution found HERE, it is not possible to set any value to match.value. Here is my code:

if (methodArgumentType.Contains("<") && methodArgumentType.Contains(">"))
        {
            var regex = new Regex("(?<=<).*?(?=>)");
            foreach (Match match in regex.Matches(methodArgumentType))
            {
                match.Value = match.Value.Replace(",", "#COMMA#");
            }
        }

Any suggestion highly appreciated.

Community
  • 1
  • 1
  • 1
    @Tushar: I don't think if the regex pattern has a problem. Actually, `match.Value` is read-only, cant be replaced. Maybe I need to do something else – Ali Ashoori Jan 07 '16 at 15:14
  • OMG. You just can do it with `methodArgumentType = Regex.Replace(methodArgumentType, @"<([^<>]+)>", m => string.Format("<{0}>", m.Groups[1].Value.Replace(",", "#COMMA#")))`. Then, `IDictionary` will turn into `IDictionary`. Is it what you want to achieve? – Wiktor Stribiżew Jan 07 '16 at 15:15
  • fixed pattern to `@"<([^<>]+)>"`. – Wiktor Stribiżew Jan 07 '16 at 15:18
  • why not just use Roslyn to get the syntax tree for the code? – Keith Hall Jan 07 '16 at 15:24
  • @stribizhev: Thanks a lot for the help. It helped a lot. Sorry, I am not that much confident with Regex concept – Ali Ashoori Jan 07 '16 at 16:33
  • @Keith Hall: I am not familiar with Rosyln. Consider that I have a String which is a list box item. Does it help me with that? – Ali Ashoori Jan 07 '16 at 16:35

1 Answers1

0

You need to replace the matched value inside the match evaluator within Regex.Replace:

var methodArgumentType = "IDictionary<string, string>";
if (methodArgumentType.Contains("<") && methodArgumentType.Contains(">"))
{
    methodArgumentType = Regex.Replace(methodArgumentType, @"<([^<>]+)>", 
        m => string.Format("<{0}>", m.Groups[1].Value.Replace(",", "#COMMA#")));
}
Console.WriteLine(methodArgumentType);
// => IDictionary<string#COMMA# string>

Here, m.Groups[1].Value will hold string, string and the replacement will be done on the input string itself, not the Regex.Match object.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563