Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split words using Regex

Tags:

c#

regex

I want to use a regex to be able to split the following string

string text = "User:George;Color:Blue;Time:100;Day:Saturday;";

into substrings so it can look like this:

User = George
Color = Blue
Time = 100
Day = Saturday

Note, however, that I want to be able to use this no matter how the text is entered or the order of the string so the string could also be like this.

string text = "Color:Blue;Day:Saturday;User:George;Time:100;";
like image 298
George Avatar asked May 09 '26 16:05

George


2 Answers

Here is a way to achieve what you need with a regex:

var text = "User:George;Color:Blue;Time:100;Day:Saturday;";
var dct = Regex.Matches(text, @"([^:;]+):([^;]+)")
    .Cast<Match>()
    .ToDictionary(p => p.Groups[1].Value, p => p.Groups[2].Value); 
var user = dct["User"];
var color = dct["Color"];
var time = dct["Time"];
var day = dct["Day"];
Console.WriteLine(user);
Console.WriteLine(color);
Console.WriteLine(time);
Console.WriteLine(day);

See IDEONE demo and here is the regex demo.

The ([^:;]+):([^;]+) captures into Group 1 one or more characters other than : and ;, then matches a colon, and then captures into Group 2 one or more characters other than ;. If values are optional, you may replace + with * (and perhaps, add ;? at the end outside the parentheses).

However, the other suggestion in the comments (splitting) looks much better, just use this dct initialization:

var dct = text.Trim(';').Split(';').Select(t=>t.Split(':')).ToDictionary(t=>t[0], t=>t[1]); 

The main point is to get keys and values, create a dictionary and then you can access dictionary values with the known keys.

like image 135
Wiktor Stribiżew Avatar answered May 11 '26 05:05

Wiktor Stribiżew


Try following method, it returns a list of KeyValuePair for your strInput:

private List<KeyValuePair<string, string>> GetKeyValuePairs(string strInput)
{
    char[] strkeyValSeparator = new char[1] { ':' };
    char[] strBlockSeparator = new char[1] { ';' };
    string[] list = strInput.Split(strBlockSeparator, StringSplitOptions.RemoveEmptyEntries);

    var lstSplitted = new List<KeyValuePair<string, string>>();

    foreach (string s in list)
    {
        string[] keyValuePair = s.Split(strkeyValSeparator, 2);

        lstSplitted.Add(new KeyValuePair<string, string>(keyValuePair[0], keyValuePair[1]));
    }

    // Sorting by Key
    lstSplitted.Sort((pair1, pair2) => pair1.Key.CompareTo(pair2.Key));

    return lstSplitted;
}

Calling the method:

string strInput = "User:George;Color:Blue;Time:100;Day:Saturday;";

var res = GetKeyValuePairs(strInput);

// Print on screen
foreach (var r in res)
    Console.WriteLine(r.Key + " = " + r.Value);
like image 28
Siyavash Hamdi Avatar answered May 11 '26 07:05

Siyavash Hamdi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!