I am trying to extract all valid hexadecimal value which represent color in a CSS code.
Specifications of HEX Color Code
- It must start with a '#' symbol.
- It can have 3 or 6 digits.
- Each digit is in range 0-F or 0-f.
Here is the sample input
#BED
{
color: #FfFdF8; background-color:#aef;
font-size: 123px;
background: -webkit-linear-gradient(top, #f9f9f9, #fff);
}
#Cab
{
background-color: #ABC;
border: 2px dashed #fff;
}
Sample output
#FfFdF8
#aef
#f9f9f9
#fff
#ABC
#fff
Explanation
#BED and #Cab satisfy the Hex Color Code criteria, but they are used as selectors and not as color codes in the given CSS. So the actual color codes are
#FfFdF8
#aef
#f9f9f9
#fff
#ABC
#fff
What I tried in python
import re
pattern = r'^#([A-Fa-f0-9]{3}){1,2}$'
n = int(input())
hexNum = []
for _ in range(n):
s = input()
if ':' in s and '#' in s:
result = re.findall(pattern,s)
if result:
hexNum.extend(result)
for num in hexNum:
print(num)
When I'm running the above code on the sample input, it is printing nothing. So what's wrong I'm doing here? Is it the matching pattern? Or is it the logic I'm applying?
Please somebody explain me!
^and$. So it will only match if the entire string is a single hex number, it won't match in the middle of the string.r'(#([A-Fa-f0-9]{3}){1,2})', now it is matching#FfFdF8but alsodF8. Now what I have to do so that it will match only#FfFdF8?df8when it doesn't begin with#.findall(). It's returning the groups instead of the entire match.findall()to get the desired output?