1

I am trying to write a regular expression by which i can replace rgb color value with hex code in a string. The string may have following types :

=> rgb(0, 0, 0) 0 0 0
=> rgb(0 100, 200)
=> 0 0 rgb(201,45,65)

First i want to access the rgb value from the string and then replace it back with hex code. So result will be :

=> #XXXXXX 0 0 0 
=> #XXXXXX
=> 0 0 #XXXXXX

3 Answers 3

2
var newstr = Regex.Replace(
                input, 
                @"rgb\([ ]*(\d+)[ ]*,[ ]*(\d+)[ ]*,[ ]*(\d+)[ ]*\)", 
                m => {
                    return "#" + Int32.Parse(m.Groups[1].Value).ToString("X2") +
                    Int32.Parse(m.Groups[2].Value).ToString("X2") +
                    Int32.Parse(m.Groups[3].Value).ToString("X2");
                }
            );
Sign up to request clarification or add additional context in comments.

Comments

0

To get the values from your string, you could do a substring based on index of "rbg(" and ")" and then do subsequent splits on " " and/or ",". Then...

See here:

http://bytes.com/topic/c-sharp/answers/268611-convert-rgb-hexadecimal

public static string ToHtml ( System.Drawing.Color color )
{
   if (System.Drawing.Color.Transparent == color)
      return "Transparent";
   return string.Concat("#", (color.ToArgb() & 0x00FFFFFF).ToString("X6"));
}

Or:

System.Drawing.Color color = System.Drawing.Color.FromArgb(longRgb);

Comments

0

How about

string str = "rgb(0 100, 200)";

int startindex = str.IndexOf("rgb(");

int endindex = str.LastIndexOf(')');

string result = str.Substring(0, startindex) 
              + "#XXXXXX" 
              + str.Substring(endindex + 1);

Tried for all 3 options you have given.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.