Regular expression for string with color RGB values in C#

In this article, learn how to extract RGB color values from the string and create System.Drawing.Color object.

Regular expression for string with color RGB values in C#:

This can be achived by using Match() function of Regex class from System.Text.RegularExpressions namespace.

String “Color Sample [A=255, R=128, G=0, B=255]”:

using System.Text.RegularExpressions;
using System.Drawing;

public class Program
    public static void Main()
	string sColorStr = "Color [A=255, R=128, G=0, B=255]";
        Match oMatch = Regex.Match(sColorStr, @"A=(?\d+),\s*R=(?\d+),\s*G=(?\d+),\s*B=(?\d+)");
	if (oMatch.Success)
	    int alpha = int.Parse(m.Groups["Alpha"].Value);
	    int red = int.Parse(m.Groups["Red"].Value);
	    int green = int.Parse(m.Groups["Green"].Value);
	    int blue = int.Parse(m.Groups["Blue"].Value);
	    Color c = Color.FromArgb(alpha, red, green, blue);

– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   Tuples in C# - Return more than one value from Method
Share this:
We will be happy to hear your thoughts

Leave a reply