Todd Main
Todd Main

Reputation: 29155

Hex Pair to Hex Shorthand

I have a bunch of Color objects (.Net). I want to convert them to Hex, which is simple enough with something like:

Dim clr As Color = Color.FromArgb(255, 0, 0)
Dim clrString = ColorTranslator.ToHtml(clr)

Is there a way in .Net or through RegEx (or some other way) that I can determine if Hex shorthand (like #F00) is available for the specified Color and then convert it to that? So for colors that can have a Hex shorthand, convert to that, otherwise, convert to Hex Pair #FF0000.

Upvotes: 0

Views: 551

Answers (2)

Dave White
Dave White

Reputation: 3461

This link describes how the Shorthand Hex Notation works.

Shorthand Hex Notation

So, in theory, any implementation that will allow you to analyze a Hex RGB value and detect "duplicate double" character values should be able to reduce it to a Hex Shorthand.

Cheers

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284927

^#([0-9A-F])\1([0-9A-F])\2([0-9A-F])\3$

This uses 3 back-references to check that each hex digit is followed by a copy. So anything with the pattern #xxyyzz (which can be converted to #xyz) matches.

Upvotes: 3

Related Questions