Regex for hexadecimal colors

1

I have a little doubt: I have a regex that captures in 3 groups (2 values per group) of a certain color, but this when I have 6 values (excluding #), I would like to know how to implement to catch < strong> 1 group when the color is for example: #333 and 3 groups when it is for example #628F61 ?

Example 1

For example, the user entered:

#fff

and regex returns 1 group with:

fff

Example 2

You entered:

#F00000

returns 3 groups:

  • F0
  • 00
  • 00
  • So far I've done this:

    #?(\w{2})(\w{2})(\w{2})
    
        
    asked by anonymous 27.03.2014 / 18:04

    3 answers

    5

    To answer the question, here is the version with regex :

    #?(([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})|([0-9a-f])([0-9a-f])([0-9a-f]))
    

    This Regex separates by 3 groups of two hex characters, or 3 groups of one hex character each.

    To use the output without too much complexity, you can concatenate groups 2 and 5, 3 and 6, 4 and 7 respectively, as only one of each pair is filled.

    #?(([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})|([0-9a-f]{3}))
    

    This is the "original" question, with 3 or 1 group.

    Simple and straightforward version without regex :

    For this type of problem, I think regex although it seems to be shorter, is of unnecessary complexity, both to be processed and to be debugged, so I decided to put this basic example using programming "traditional".

    It works with or without # at the beginning, and with 3 or 6 digits.

    color = "#bacc01"
    
    if color[0]=="#":
       color = color[1:]
    
    if len(color) == 3:
       r = color[0]
       g = color[1]
       b = color[2]
    
    else:
       r = color[0:2]
       g = color[2:4]
       b = color[4:6]
    
    print( "red  ", r )
    print( "green", g )
    print( "blue ", b )
    

    Output:

    red   ba
    green cc
    blue  01
    

    To adapt to #abc you can leave in a group only, just change whatever is inside the if inicial.

        
    27.03.2014 / 18:30
    1

    Here's the expression:

    ^#((\w{2})(\w{2})(\w{2})|(\w{3}))$
    

    I basically added a new condition for the 3-character case, and also a $ , indicating that the string should end there.

    As a bonus, here's an expression to detect a color string with 3 or 6 characters (but not the 3 groups):

    ^#(?:[0-9a-f]{3}){1,2}$
    
        
    27.03.2014 / 18:15
    1

    This expression should work for you:

    ^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})|([0-9a-fA-F]{3})$
    

    It will return a color group as #fff 333 #333 . Or else, it will return three groups for colors like #ffffff ff33FF #333333 .

    Note also that the expression has the character ^ at the beginning of the line and the $ at the end, it is at your disposal to remove them. This expression accepts only hexadecimal characters and # is optional.

        
    27.03.2014 / 21:31