Mak
Mak

Reputation: 161

Extract Hex colors from css using java

I am simply trying to get all the Hex colors values form a css file. The hex value could be #fff or #ffffff so here are the regular expressions i used for this

but not working at all.

i am expecting the result as

#996633 #333 #ccc #969696 ....

But getting nothing, any idea where i am going wrong?

Here is the code:

final String HEX_PATTERN_STRING = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
Pattern pattern = Pattern.compile(HEX_PATTERN_STRING);
try {
        final URL CSS = new URL("https://maxcdn.bootstrapcdn.com/.../bootstrap.min.css");
        URLConnection data = CSS.openConnection();
        StringBuilder result = new StringBuilder();
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        data.getInputStream())
        )) {
            in.lines().forEach(result::append);

            Matcher matcher = pattern.matcher(result);
            while (matcher.find()) {
                System.out.println(matcher.group(0));
            }
            System.out.println("Done");
        }

    } catch (IOException ex) {
    }

Upvotes: 4

Views: 565

Answers (2)

neoexpert
neoexpert

Reputation: 474

I'm using this pattern:

Pattern PATTERN_HEXCOLOR = Pattern.compile(
    "#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})\\b");

It does accept color values like

#FFF
#FFFFFF

And ignores invalid color values like

#FFFF or #FFFFFFF

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

Note your pattern contains ^ (start of string) and $ (end of string) anchors, requiring a whole string match.

You need to remove these anchors.

You cannot use regex delimiters like /.../ either, as in Java regex, you can pass the modifiers as (?i) inside the pattern, or with the help of Pattern.CASE_INSENSITIVE flag (usually, with Pattern.UNICODE_CASE).

Also, if you do not need the numbers only, you may turn the capturing group into a non-capturing (?:...).

Use

final String HEX_PATTERN_STRING = "#(?:[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})";

Upvotes: 2

Related Questions