Dr Pepper Registered User
#1

Hi All,

I need a regular expression to convert 3-digit hex color codes in html to 6 digit ones. I want to do this because when I put html text into swing text components, the 3-digit versions don't seem to be recognised. I know how the 3-digit codes work by the way - the 3-digit code "#ABC;" is the same as the 6-digit code "#AABBCC;". I'm looking for a regex to do that simple conversion and expand/replace all instances in a given string.

Just to show some sort of effort on my part, I think this might find 3-digit color codes:

String s = html.replaceAll("#[0-9a-fA-F]{3};","????");

I have no idea how to grab the A, B and C from the input string and put them into the output results. Of course, let me know if you know of any other entirely different way of doing this!

In case you're wondering, this is not a homework assignment. I've been programming for many years but have managed to spoof my way thus far with little or no grasp of regular expressions. They just are something I've never really gotten my head around! As a work-around, I started writing a 'simple' method to loop through the string looking for # symbols and what comes after them, yadda, yadda, yadda... but it got very large and ugly and I don't trust it. Plus, it's Monday and I'm just not up for that kind of thing

Thanks,
Brian

t1mm Registered User
#2

1 person has thanked this post
Dr Pepper Registered User
#3

Thanks for the suggestion t1mm.

However, I persevered with the regex approach for a bit longer and came up with a nice one-liner solution, using some tips from this page (capturing groups from the match expression).

str.replaceAll("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F]);","#$1$1$2$2$3$3;");


$1 refers to the first group (in brackets), $2 refers to the second, and so on. Seems to do the job very nicely!

2 people have thanked this post
t1mm Registered User
#4

Much cleaner - nicely done

Procasinator Registered User
#5

Should the last range not be A-F instead of A-f?

1 person has thanked this post
Dr Pepper Registered User
#6

Correct! Thanks, nice catch. I'd only tested HTML documents with lower-case hex codes so that could have been a headache if it stopped working again on an upper-case code.

#7

FYI: There's an excellent RegEx utility here.

There's the online version, or what I much prefer, an Eclipse plugin.

Linky

1 person has thanked this post
murphaph Registered User
#8

CreepingDeath said:
FYI: There's an excellent RegEx utility here.

There's the online version, or what I much prefer, an Eclipse plugin.

Linky


That eclipse plugin is soooo handy the way it matches with colour coding. Very intuitive. Always install that as part of any fresh eclipse install

You can also copy the regex and simultaneously escape it for use in java and paste straight into your java code. With long regexes it can be easy to make a mistake escaping them.

Want to share your thoughts?

Login here to discuss!