Search code examples
c#regexregex-group

Get a regex expression for a key value pair separated by comma


I would like to get the regex expression for a key-value pair separated by comma.

input: "tag.Name:test,age:30,name:TestName123"

This is my attempt so far

string pattern = @".*:.*" 

(I guess that .* indicates anything multiple times, followed by : and again anything multiple times, if I include a comma at the end ,*

string pattern = @".*:.*,*"

I assume is the same thing, but it didn't work for me, the final result can be accomplish with Linq but I would like to not parse the input

A sample of my output

INPUT

string input = "tags.tagName:Tag1,tags.isRequired:false"
var finaRes = input.Split(',').Select(x => x.Split(':')).Select(x => new { Key = x.First(), Value= x.Last()});

OUTPUT:

Key              Value
---------------|-------
tags.tagName   |  Tag1 
tags.isRequired|  false 

Solution

  • You can use this regex (demo is here)

    (?<key>[^:]+):(?<value>[^,]+),?
    

    Explanation:

    (?<key>[^:]+) // this will match a 'key' - everything until colon char
    (?<value>[^,]+) // this  will match a 'value' - everything until comma char
    

    C# example:

    var regex = new Regex("(?<key>[^:]+):(?<value>[^,]+),?");
    var input = "tag.Name:test,age:30,name:TestName123";
    
    var matches = regex.Matches(input);
    
    foreach (Match match in matches)
    {
        Console.Write(match.Groups["key"]);
        Console.Write(" ");
        Console.WriteLine(match.Groups["value"]);
    }
    

    Output will be:

    tag.Name test
    age 30
    name TestName123
    

    Demo