CSS colors are defined using a hexadecimal (HEX) notation for the combination of Red, Green, and Blue color values (RGB).

Specifications of HEX Color Code

■ It must start with a '#' symbol.

■ It can have $3$ or $\boldsymbol{6}$ digits.

■ Each digit is in the range of $\mbox{o}$ to $\mbox{F}$. ($1,2,3,4,5,6,7,8,9,0,A,B,C,D,E$ and $\mbox{F}$).

■ $A-F$ letters can be lower case. ($a,b,c,d,e$ and $\mbox{f}$ are also valid digits).

Examples  

Valid Hex Color Codes
#FFF 
#025 
#F0A1FB 

Invalid Hex Color Codes
#fffabg
#abcf
#12365erff

You are given $N$ lines of CSS code. Your task is to print all valid Hex Color Codes, in order of their occurrence from top to bottom. 

CSS Code Pattern

Selector
{
	Property: Value;
}

Input Format

The first line contains $N$, the number of code lines.

The next $N$ lines contains CSS Codes.  

Constraints

$0<N<50$

Output Format

Output the color codes with '#' symbols on separate lines.

Sample Input
11
#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. 

Hence, the valid color codes are:

#FfFdF8

#aef

#f9f9f9

#fff

#ABC

#fff

Note: There are no comments ( // or /* */)  in CSS Code.

Source: hackerrank | Difficulty: EASY


Solutions:
import re
pattern = re.compile('(?<!^)(#[0-9A-F]{6}|#[0-9A-F]{3})', re.IGNORECASE)
for _ in range(int(input())):
	for m in pattern.finditer(input()):
		print(m.group(0))


st = ''
n = int(input())
for i in range(n):
	st += input()
arr = []
flag = 0
tmp = ''
for c in st:
	if c == '{':
		flag = 1
		continue
	elif c == '}':
		flag = 0
		arr.append(tmp)
		tmp = ''
		continue
	elif flag == 1:
		tmp += c
arr2 = []
for e in arr:
	flag = 0
	tmp = ''
	for c in e:
		if c == '#':
			flag = 1
			tmp += '#'
			continue
		elif c not in '1234567890abcdefABCDEF' and flag == 1:
			flag = 0
			arr2.append(tmp)
			tmp = ''
			continue
		elif flag == 1:
			tmp += c
for i in arr2:
	if len(i) == 4 or len(i) == 7:
		print(i)


import string

def getIndices(string1, target):
	result = []
	for i in range(len(string1)):
		if string1[i] == target:
			result.append(i)
	return result

def isHex(string1):
	for i in string1:
		if i not in string.hexdigits:
			return False
	else:
		return True
N = int(input())
start = False
for i in range(N):
	line = input()
	length = len(line)
	if '{' in line:
		start = True
		continue
	elif '}' in line:
		start = False
	if start:
		indices = getIndices(line, '#')
		if len(indices) != 0:
			for i in indices:
				if i + 6 <= length and isHex(line[i + 1:i + 7]):
					print(line[i:i + 7])
				elif i + 3 <= length and isHex(line[i + 1:i + 4]):
					print(line[i:i + 4])


import re
for i in range(int(input())):
	pattern = re.findall('(?<!^)(#[\\dA-F]{6}|#[\\dA-F]{3})(?!$)', input(), flags=re.I)
	if pattern != []:
		print('\n'.join((p for p in pattern)))


num_lines = int(input())
css = ''
for _ in range(num_lines):
	css += input()
i = 0
can_search = False
hex_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f']
while i < len(css):
	if css[i] == '{':
		can_search = True
	if css[i] == '}':
		can_search = False
	if can_search:
		if css[i] == '#':
			validHex = False
			hex = '#'
			a = 1
			while css[i + a] in hex_digits:
				hex += css[i + a]
				a += 1
			if len(hex) == 4 or len(hex) == 7:
				print(hex)
	i += 1


N = int(input())
(inside_curly, h) = (0, 0)
s = ''
code = ''
for _ in range(N):
	r = input()
	s += r

def is_hex(c):
	return (len(c) == 3 or len(c) == 6) and all([x in 'abcdefABCDEF0123456789' for x in c])
for c in s:
	if c == '{':
		inside_curly += 1
	if c == '}':
		inside_curly -= 1
	if inside_curly == 0:
		continue
	if c == '#':
		h += 1
	if h > 0 and c != '#':
		code += c
	if h > 0 and c not in 'abcdefABCDEF0123456789#':
		if is_hex(code[:-1]):
			print('#' + code[:-1])
		h = 0
		code = ''


import re
n = int(input())
need = 0
for i in range(n):
	for x in re.split('[;,\\s\\n:\\)\\(\\[\\]]', input()):
		if x == '{':
			need = 1
		if x == '}':
			need = 0
		if re.match('^\\#[0-9a-fA-F]{3}$', x) or re.match('^\\#[0-9a-fA-F]{6}$', x):
			if need == 1:
				print(x)


import re

def isColor(t):
	if len(t) != 4 and len(t) != 7:
		return False
	if t[0] != '#':
		return False
	return set(t[1:]).issubset(set('0123456789abcdefABCDEF'))
n = int(input())
inside = False
for _ in range(n):
	s = input().strip()
	tokens = re.split(':|;|\\)|\\(|,| ', s)
	for token in tokens:
		if token == '{':
			inside = True
		elif token == '}':
			inside = False
		elif inside and isColor(token):
			print(token)


import re
__author__ = 'namii'
rgb_re = re.compile('#[0-9abcdefABCDEF]{6}|#[0-9abcdefABCDEF]{3}')
N = int(input())
for _ in range(N):
	line = input()[1:]
	matches = rgb_re.findall(line)
	for item in matches:
		print(item)


import re
colorReg = re.compile('(?<=[ :,])#(?:[0-9a-fA-F]{3}){1,2}')
for i in range(int(input())):
	line = input()
	mo = colorReg.findall(line)
	for l in mo:
		print(l)


import re
nn = int(input())
l = []
ans = []
for i in range(nn):
	try:
		l.append(input())
	except EOFError:
		break
pattern = '#[a-fA-F0-9]{3,6}[;,)]'
for p in l:
	p = str(p)
	ans = re.findall(pattern, p)
	for i in range(len(ans)):
		print(re.sub('[;,)]', '', ans[i]))


import re
pattern = re.compile('(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3}))')
n = int(input())
outside_scope = True
for i in range(0, n):
	inp = input()
	if '{' in inp:
		outside_scope = False
		continue
	elif '}' in inp:
		outside_scope = True
	if outside_scope:
		continue
	for match in re.findall(pattern, inp):
		print(match[0])


import re
n = int(input())
p = re.compile('^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$')
for i in range(n):
	s = input()
	if s not in ['{', '}'] and len(s.split(':')) > 1:
		c = re.compile('#{1}.{6}|#{1}.{3}')
		t = c.findall(s)
		for sx in t:
			if p.search(sx):
				print(sx)


import re
n = int(input())
r1 = re.compile('(#[0123456789ABCDEFabcdef]{6})|(#[0123456789ABCDEFabcdef]{3})')
for i in range(n):
	line = input()
	if line == '':
		continue
	if line[0] == '#':
		continue
	m = r1.findall(line)
	for mi in m:
		for mi2 in mi:
			if mi2 == '':
				continue
			print(mi2)


valid_chars = set(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'])

def valid(line, start):
	range_count = 6
	if len(line) - start < 6:
		if len(line) - start < 3:
			return -1
		range_count = 3
	three_valid = False
	for i in range(range_count):
		if i == range_count - 1:
			if line[start + 1] in valid_chars:
				print(line[start - 1:start + range_count])
				return range_count
			return -1
		elif line[start + i] not in valid_chars:
			if i > 1:
				print(line[start - 1:start + 3])
				return 3
			return -1
	return -1
lines = int(input())
selected = False
for _ in range(lines):
	line = input()
	index = 0
	end_selection = len(line)
	if line.find('{') != -1:
		selected = True
		index = line.find('{') + 1
	if selected == False:
		continue
	if line.find('}') != -1:
		end_selection = line.find('}')
		selected = False
	for i in range(index, end_selection):
		hashmark = line.find('#', index)
		if hashmark == -1:
			break
		valid_index = valid(line, hashmark + 1)
		if valid_index != -1:
			index = valid_index + hashmark
		else:
			index = hashmark + 1
		if index > len(line) - 3:
			break


import re
lines = int(input().strip())
fulltext = ''
for line in range(lines):
	for s in input():
		fulltext += s
r = re.findall(':(.*?);', fulltext)
for x in r:
	for x2 in x.split():
		rematch = re.match('#(?:[A-Fa-f0-9]{3}){1,2}', x2)
		if rematch:
			print(rematch.group(0))


import re
numLines = int(input())
for i in range(numLines):
	line = str(input())
	match = re.search('^#', line)
	if not match:
		matches = re.findall('(#[A-Fa-f0-9]{6}|#[A-Fa-f0-9]{3})', line)
		for match in matches:
			print(match)


s = ''
for _ in range(int(input())):
	s += input()
W = set('0123456789abcdefABCDEF')
on = 0
i = 0
while i < len(s):
	x = s[i]
	if x == '{':
		on = 1
	if x == '}':
		on = 0
	if x == '#' and on:
		t = '#'
		j = 0
		while i + j + 1 < len(s) and s[i + j + 1] in W:
			t += s[i + j + 1]
			j += 1
		i += j
		if j == 3 or j == 6:
			print(t)
	i += 1


import re
n = int(input().strip())
inside = False
for _ in range(n):
	line = input()
	for el in line.split(' '):
		if el == '{':
			inside = True
			continue
		elif el == '}':
			inside = False
			continue
		elif inside:
			found = re.search('\\#[0-9a-fA-F]{3,6}', el)
			if found:
				print(found.group(0))


import re
from functools import reduce
N = int(input())
txt = reduce(lambda a, b: a + '\n' + b, [input() for _ in range(N)])
res = re.findall('(?<=.)(#([0123456789abcdefABCDEF]{3}){1,2})(?=.)', txt)
for r in res:
	print(r[0])


import re
N = int(input())
hexcode = re.compile('(#[0-9a-f]{3}(?:[0-9a-f]{3})?)', re.IGNORECASE)
for _ in range(N):
	line = input()
	if ':' in line:
		match = hexcode.findall(line)
		if match:
			for m in match:
				print(m)


import re
hex_color = re.compile('#([0-9A-Fa-f]{3}){1,2}')
n = int(input())
bracket_level = 0
for i in range(n):
	s = input().strip()
	if s.endswith('{'):
		bracket_level += 1
		continue
	elif s == '}':
		bracket_level -= 1
		continue
	if bracket_level > 0:
		for m in hex_color.finditer(s):
			print(m.group())


import re
n = int(input())
s = ''
ins = 0
for i in range(n):
	k = input()
	p = 0
	if '{' in k:
		ins = 1
		p = 1
	if '}' in k:
		ins = 0
		p = 1
	if ins == 1 and p == 0:
		s += k
for i in re.findall('#[0-9a-fA-F]{3,6}', s):
	if len(i) == 4 or len(i) == 7:
		print(i)


import re
for _ in range(int(input())):
	for x in re.findall('(?<!\\A)#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})(?=\\W)', input()):
		print('#{}'.format(x))


import re
hex_color_format = '#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})'
inside_brackets = '\\{(.*?)\\}'
number_of_lines = int(input())
lines = []
for i in range(number_of_lines):
	lines.append(str(input()))
css_code = '\n'.join(lines)
blocks = re.findall(inside_brackets, css_code, re.DOTALL)
colors = re.findall(hex_color_format, '\n'.join(blocks), re.DOTALL)
for color in colors:
	print('#' + str(color))


from re import findall
colors = []
N = int(input())
for _ in range(N):
	line = input()
	se = findall('.(#(?:[0-9A-Fa-f]{6}|[0-9A-Fa-f]{3}))', line)
	if se:
		colors += se
print('\n'.join(colors))


import sys
import re
n = int(input())
css = ''.join(sys.stdin.readlines())
inbrackets = False
parsedcss = ''
for c in list(css):
	if not inbrackets and c == '{':
		inbrackets = True
		continue
	elif inbrackets and c == '}':
		inbrackets = False
		continue
	if inbrackets:
		parsedcss += c
regex = re.compile('#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3}')
print('\n'.join(regex.findall(parsedcss)))


import re
n = int(input())
text = ''
for i in range(n):
	text += input() + '\n'
match_objects = re.findall('(#[0-9a-fA-F]{6}[;|,||)]|#[0-9a-fA-F]{3}[;|,||)])', text)
for i in match_objects:
	print(i.replace(',', '').replace(';', '').replace(')', ''))


import re
pattern = re.compile('(#[0-9A-Fa-f]{3}|#[0-9A-Fa-f]{6})[^0-9A-Fa-f]')
n = int(input())
in_css = False
colors = []
for _ in range(n):
	line = input()
	if in_css:
		colors.extend(pattern.findall(line))
		if '}' in line:
			in_css = False
		if '{' in line:
			in_css = True
	else:
		if '{' in line:
			in_css = True
		if '}' in line:
			in_css = False
for i in colors:
	print(i)


import re
for _ in range(int(input())):
	l = input()
	if l.find(':') != -1:
		for i in re.findall('#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})\\b', l):
			print(i)


import re
l = []
for _ in range(int(input())):
	l.append(input())
s = '\n'.join(l)
matches = re.findall('(#(?:[a-fA-F0-9]{1,2}){3})(?!\\s*\\{)', s)
print('\n'.join(list(matches)))


def ok(s):
	s = s.strip().lower()[1:]
	if len(s) == 6 or len(s) == 3:
		for c in s:
			if c not in [str(x) for x in range(10)] + [x for x in 'abcdef']:
				return False
		return True
	return False

def proc(s, stack):
	ss = ''
	for i in range(len(s)):
		if s[i] == '{':
			stack.append('{')
		elif s[i] == '}':
			stack.pop()
		elif s[i] == '#':
			ss += '#'
		elif ss != '':
			if s[i].isdigit() or s[i].isalpha():
				ss += s[i]
			else:
				if ok(ss) and len(stack) > 0 and (stack[-1] == '{'):
					print(ss)
				ss = ''
	if ss != '' and len(stack) > 0 and (stack[-1] == '{') and ok(ss):
		print(ss)
		ss = ''
N = int(input().strip())
stack = []
for _ in range(N):
	s = input().strip()
	proc(s.strip(), stack)


import re
for _ in range(int(input())):
	S = re.findall('(?!^#)\\#[0-9a-fA-F]{6}|(?!^#)\\#[0-9a-fA-F]{3}', str(input()))
	for i in S:
		print(i)


import sys
import re
for line in sys.stdin:
	T = re.compile('#([a-fA-F0-9]{3,6})[;,)]')
	for m in T.finditer(line):
		print(line[m.start():m.end() - 1])


import re
n = int(input())
l = list((input() for i in range(n)))
s = ''.join(l).replace(' ', '').replace('\t', '')
m = re.findall('(?<=#)([a-fA-F_0-9]{6}|[a-fA-F_0-9]{3})(?!\\{)', s)
for mm in m:
	print('#{}'.format(mm))


import re
a = ''
for i in range(int(input())):
	a += input().strip('\n')
print('\n'.join((i for i in re.findall('#[a-fA-F0-9]*', str(re.findall('\\{.*?\\}', a))) if len(i) == 4 or len(i) == 7)))


import re
n = int(input())
for _ in range(n):
	m = re.compile('[^:]+:(.+)').match(input())
	if m:
		value = m.group(1)
		for s in re.findall('[^#]*(#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3}))', value):
			print(s)


import re
css = ''
n = int(input())
for i in range(0, n):
	css = css + input() + '\n'
inside_brackets = re.findall('\\{.*?\\}', css, flags=re.DOTALL)
for attributes in inside_brackets:
	li = re.findall('#(?:[a-fA-F0-9]{3}|[a-fA-F0-9]{6})\\b', attributes)
	for x in li:
		print(x)


import re
css = ''
N = int(input())
for i in range(N):
	css += input()
noHeaders = ''.join(re.findall('{[\\w\\W]*?}', css))
allHexes = re.findall('(#[0-9a-fA-F]{6})|(#[0-9a-fA-F]{3})', noHeaders)
allHexesList = []
for each in allHexes:
	for el in each:
		if el != '':
			print(el)


import re
N = int(input())
CSS = [input() for i in range(N)]
C = '0123456789abcdefABCDEF'
for i in range(N):
	row = re.findall('(?!\\A)(#[a-fA-f_0-9]{6}|#[a-fA-f_0-9]{3})', CSS[i])
	if row != []:
		for j in row:
			print(j)


import re
n = int(input())
s = []
for i in range(n):
	s.append(input())
string = ''.join(s)
f = re.findall('{([^}]*)}', str(s))
for s in f:
	res = re.findall('#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})', s)
	if res:
		for r in res:
			print('#' + str(r))


import sys
N = input()
full = list(sys.stdin.read().split())
a = [full[i] for i in range(len(full)) if '#' in full[i] and full[i + 1] != '{']
for i in range(len(a)):
	a[i] = a[i][a[i].find('#'):]
	for j in range(1, len(a[i])):
		t = ord(a[i][j])
		if t < ord('0') or (t > ord('9') and t < ord('A')) or (t > ord('Z') and t < ord('a')) or (t > ord('z')):
			a[i] = a[i][:j]
			break
for i in range(len(a)):
	if len(a[i]) != 4 and len(a[i]) != 7:
		a[i] = 0
		continue
	for j in range(1, len(a[i])):
		t = ord(a[i][j])
		if t > ord('f') and t < ord('z') or (t > ord('F') and t < ord('Z')):
			a[i] = 0
			break
for x in a:
	if x != 0:
		print(x)


import re
text = []
sol = []
L = int(input())
for i in range(0, L):
	text.extend(input().split())
REGEXP = re.compile('[A-Za-z:]*#[0-9a-fA-F]{3,6}[;,)]*$')
n = len(text)
text.extend('NULL')
for i in range(0, n):
	if re.search(REGEXP, text[i]) and text[i + 1] != '{':
		sol.append(text[i])
for i in range(0, len(sol)):
	sol[i] = sol[i].replace(';', '')
	sol[i] = sol[i].replace(',', '')
	sol[i] = sol[i].replace(')', '')
	if sol[i][0] != '#':
		j = sol[i].index('#')
		sol[i] = sol[i][j:]
for i in sol:
	print(i)


import sys, re
lines = int(input().strip())
for i in range(lines):
	line = str(input())
	if re.match(' *?\\#', line):
		pass
	else:
		match_list = re.findall('\\#[\\dA-Fa-f]{6}[^\\dA-Fa-f]|\\#[\\dA-Fa-f]{3}[^\\dA-Fa-f]', line)
		if match_list != []:
			for m in match_list:
				if len(m) == 8:
					print(m[:7])
				else:
					print(m[:4])


import sys
import re
re_hex = re.compile('[:,].*?(#[0-9A-Fa-f]{3}(?:[0-9A-Fa-f]{3})?)\\b')
for s in re_hex.findall(sys.stdin.read()):
	print(s)


import re
n = int(input())
for i in range(n):
	s = input()
	p = re.compile('^(#[A-Fa-f0-9]{6})|^(#[A-Fa-f0-9]{3})')
	g_reject = p.findall(s)
	p = re.compile('(#[A-Fa-f0-9]{6})|(#[A-Fa-f0-9]{3})')
	g_all = p.findall(s)
	if g_reject:
		continue
	elif g_all:
		for e in g_all:
			if e[0] and e[0] not in g_reject:
				print(e[0])
			elif e[1] and e[0] not in g_reject:
				print(e[1])


n = int(input())
for i in range(n):
	st = input()
	count = -1
	for j in st:
		count += 1
		if j == '#' and count != 0:
			c = 0
			temp = count + 1
			res = ''
			while 'a' <= st[temp] <= 'f' or 'A' <= st[temp] <= 'F' or '0' <= st[temp] <= '9':
				res += st[temp]
				c += 1
				temp += 1
			if c == 3 or c == 6:
				print('#' + res)


import re
N = int(input())
input_string = [input() for index in range(N)]
input_string = '\n'.join(input_string)
(entries, colcodes) = (re.findall('(:.*;)', input_string), [])
for entry in entries:
	colcodes.extend(re.findall('(#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3})', entry))
for color in colcodes:
	print(color)


import re
n = int(input())
for _ in range(n):
	match = re.findall('(?<!^)#[a-fA-F0-9]{3,6}', input())
	if match:
		for m in match:
			print(m)


S = ''
c = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f']

def validate(s):
	l = len(s)
	if l == 3 or l == 6:
		for i in s:
			if i not in c:
				return False
		return True
	else:
		return False
Ans = []
bkop = False
for i in range(int(input())):
	if not bkop:
		a = input()
		if '{' in a:
			bkop = True
	else:
		a = input()
		if '}' in a:
			bkop = False
		while a.find('#') != -1:
			p = a.find('#')
			i = p
			while a[i] != ' ' and a[i] != ';' and (a[i] != ',') and (a[i] != '\n') and (a[i] != ')'):
				i += 1
			if validate(a[p + 1:i]):
				print(a[p:i])
			a = a[i + 1:]
list(map(print, Ans))


import re
for _ in range(int(input())):
	matches = re.findall('#(?:[0-9a-fA-F]{3}){1,2}[;|,|\\)]', input())
	for i in matches:
		print(i[:-1])


import re
n = int(input())
results = []
for i in range(n):
	for y in re.findall('(#[0-9a-fA-F]{6}[;(,)]|#[0-9a-fA-F]{3}[;(,)])', input()):
		print(y.replace(';', '').replace(')', '').replace(',', ''))


import re
for _ in range(int(input())):
	t = input()
	if re.match('\\s', t):
		for e in re.finditer('#([0-9a-f]{6}|[0-9a-f]{3})', t, re.I):
			print(e.group())


import re
s = ''
valid = 'a-fA-F0-9'
for _ in range(int(input())):
	s = s + ' ' + input()
[print(x.group()) for x in re.finditer('(?<!\\w)(#[' + valid + ']{3})([' + valid + ']{3})?(?!\\w| \\{)', s)]


import sys
import re

def findhex(data):
	hexmatch = re.compile('(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}))[^0-9a-fA-F]')
	return [res[0] for res in hexmatch.findall(data)]

def run():
	linematch = re.compile('[a-zA-Z0-9]:')
	for line in sys.stdin.readlines():
		if linematch.search(line) is not None:
			for val in findhex(line):
				print(val)
run()


from re import findall
for line in range(int(input())):
	matches = findall('#[0-9a-fA-F]{3,6}(?=.*;)', input())
	for match in matches:
		print(match)


import re
p = re.compile('(?<=.)(\\#[a-fA-F0-9]{3}([a-fA-F0-9]{3})?)(?=.)')
N = int(input())
for _ in range(N):
	line = input()
	for m in p.finditer(line):
		print(m.group(0))


import re
N = int(input())
begin_block = '^#.*'
colors = '#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}'
for i in range(N):
	line = input()
	if not re.findall(begin_block, line):
		s = re.findall(colors, line)
		for i in s:
			if i != '':
				print(i)


import re
text = ''
for _ in range(int(input())):
	text += input()
for x in re.findall('\\{.*?\\}', text):
	a = re.findall('#(?:[a-fA-f0-9]{3}|[a-fA-f0-9]{6})\\b', x)
	if a:
		print('\n'.join(a))


import re
regex = re.compile('(#[0-9a-fA-F]{3,6})[^0-9a-fA-F]?')
brack = False
for _ in range(int(input())):
	line = input()
	if '{' in line:
		brack = True
		line = line.split('{')[1]
	if brack:
		brack = True
		f = regex.findall(line)
		if f:
			print('\n'.join(f))
	if '}' in line:
		brack = False


import re
number = int(input())
s = ''
for i in range(number):
	s += input() + '\n'
r = re.compile('#[0-9A-Fa-f]{3,6}[;,)]')
for el in r.findall(s):
	print(el[0:-1])


import re
pattern = re.compile('(#[a-fA-F\\d]{6}|#[a-fA-F\\d]{3});*')
for i in range(int(input())):
	line = input()
	if line.startswith('#'):
		continue
	for match in re.findall(pattern, line):
		print(match)


import sys
import re

def vn():
	num = int(sys.stdin.readline())
	reg = re.compile('.(#[A-Fa-f0-9]{3,6})')
	while num:
		s = sys.stdin.readline()
		res = reg.findall(s)
		for color in res:
			sys.stdout.write(color + '\n')
		num -= 1
	return

def main():
	vn()
	return
main()


import re

def printIt(stuff):
	pattern = stuff.group()[:-1]
	print(pattern)
N = int(input())
css = ''
for i in range(0, N):
	css += ''.join(input().split())
re.sub('(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3})(\\s)*[^{]', printIt, css)


import re
n = int(input())
for t in range(n):
	s = input()
	match_result = re.findall('(#[0-9A-Fa-f]{3}|#[0-9A-Fa-f]{6})(?:[;,.)]{1})', s)
	for i in match_result:
		if i != '':
			print(i)


import re
for i in range(int(input())):
	m = re.findall('(?<=.)#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})', input())
	for i in m:
		print('#' + i)


N = int(input())
for i in range(N):
	line = input()
	if not ':' in line:
		continue
	index = line.find('#')
	while index != -1:
		chars = [c for c in line[index + 1:index + 7]]
		cleaned = []
		for c in chars:
			try:
				val = int(c, 16)
				cleaned.append(c)
			except ValueError:
				break
		if len(cleaned) == 3 or len(cleaned) == 6:
			print('#' + ''.join(cleaned))
		index = line.find('#', index + 1)


import re
n = int(input().strip())
for i in range(n):
	mo = re.findall('(?<=.)#[0-9,A-F,a-f]{6}|(?<=.)#[0-9,A-F,a-f]{3}', input())
	for i in mo:
		print(i)


import re
regex = '(?<=:| )#[0-9a-fA-F]{3}(?=[,;\\) ])|(?<=:| )#[0-9a-fA-F]{6}(?=[,;\\) ])'
n = int(input())
results = []
for i in range(n):
	line = str(input())
	results += re.findall(regex, line)
for result in results:
	print(result)


import re
n = int(input())
css = []
for _ in range(n):
	match = re.findall('(?<!^)(#{1}(([A-Fa-f0-9]{6})|([A-Fa-f0-9]{3})))', input())
	if match:
		color = [c[0] for c in match]
		css.extend(color)
print(*css, sep='\n')


import re

def main():
	N = int(input())
	inBlock = False
	for _ in range(N):
		S = input()
		dealAlready = False
		for i in range(len(S)):
			if S[i] == '{':
				inBlock = True
				m = re.findall('#[a-fA-F\\d]{3,6}', S[i:])
				for res in m:
					print(res)
				dealAlready = True
			elif S[i] == '}':
				inBlock = False
		if inBlock and (not dealAlready):
			m = re.findall('#[a-fA-F\\d]{3,6}', S)
			for res in m:
				print(res)
main()


import re
import sys
RE = '(.*[^#])?(?P<color>#(([a-fA-F0-9]{6}(?![a-fA-F0-9]))|([a-fA-F0-9]{3}(?![a-fA-F0-9]))))'
for line in sys.stdin.readlines():
	if len(line) > 3:
		words = re.split('\\s', line[1:])
		for word in words:
			word = word.strip()
			if word:
				m = re.match(RE, word)
				if m:
					print(m.group('color'))


import re
for i in range(int(input())):
	for el in re.findall('(#[A-Fa-f\\d]{6}|#[A-Fa-f\\d]{3})[,;\\)]', input()):
		print(el)


from re import compile, findall
from sys import stdin
REGEX = compile('(#[0-9a-fA-F]{3}|#[0-9a-fA-F]{6})[;,)]')
[print(match) for match in findall(REGEX, stdin.read())]


hexdigs = set('0123456789abcdefABCDEF')
nlines = int(input())
inbrace = False
for _ in range(nlines):
	line = input()
	if '{' in line:
		inbrace = True
	elif '}' in line:
		inbrace = False
	elif inbrace:
		start = 0
		line += ' ' * 7
		while True:
			ind = line.find('#', start)
			if ind == -1:
				break
			if all((c in hexdigs for c in line[ind + 1:ind + 4])) and (not line[ind + 4].isalnum()):
				print(line[ind:ind + 4])
			elif all((c in hexdigs for c in line[ind + 1:ind + 7])) and (not line[ind + 7].isalnum()):
				print(line[ind:ind + 7])
			start = ind + 1


import re
n = int(input())
for _ in range(n):
	s = input()
	if ':' not in s:
		continue
	for color in re.findall('#[0123456789abcdefABCDEF]{3,6}', s):
		print(color)


import re
for i in range(int(input())):
	matches = re.findall('(?<= |:)((?:#)(?:[0-9A-Fa-f]{1,2}){3,4})', input())
	if matches:
		for match in matches:
			print(match)


def isValidHex(s):
	valid = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f']
	for x in range(1, len(s)):
		if s[x] not in valid:
			return False
	return True
N = int(input())
for i in range(0, N):
	s = input()
	if s.startswith('#'):
		continue
	x = 0
	while x < len(s):
		if s[x] == '#':
			sub1 = s[x:x + 4]
			sub2 = s[x:x + 7]
			if isValidHex(sub2):
				print(sub2)
			elif isValidHex(sub1):
				print(sub1)
		x += 1


import re
input_string = ''
n = int(input())
for i in range(0, n):
	temp = input()
	input_string = input_string + temp
inside_brackets = re.findall('\\{.*?\\}', input_string, flags=re.DOTALL)
for attributes in inside_brackets:
	lists = re.findall('#(?:[a-fA-F0-9]{3}|[a-fA-F0-9]{6})\\b', attributes)
	for ele in lists:
		print(ele)


symbols = '1234567890abcdefABCDEF'

def validate(colour):
	symbols = '1234567890abcdefABCDEF'
	if len(colour) == 6 or len(colour) == 3:
		for char in colour:
			if char not in symbols:
				return False
		return True
	else:
		return False
lines = []
colours = []
properties = False
for line in range(int(input())):
	line_in = input()
	if '}' in line_in:
		properties = False
	if properties:
		lines.append(line_in.strip())
	if '{' in line_in:
		properties = True
for line in lines:
	colour = ''
	find_colour = False
	for char in line:
		if char not in symbols:
			find_colour = False
			if validate(colour):
				colours.append('#' + colour)
			colour = ''
		if find_colour:
			colour += char
		if char == '#':
			find_colour = True
for item in colours:
	print(item)


import re
N = int(input())
css = ''.join([input() for i in range(N)])
selectors = re.findall('{(.*?)}', css)
for x in selectors:
	hex = re.findall('(:|,|\\(|).*?(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}).*?(;|,|\\))', x)
	for i in hex:
		print(i[1])


import re
exp = re.compile('(?<!^)#[A-Fa-f0-9]{3,6}')
line_count = int(input().strip())
for x in range(line_count):
	line = input().strip()
	for match in re.findall(exp, line):
		print(match)


from re import compile
pattern = compile('(#([a-fA-F0-9]{3}|[a-fA-F0-9]{6}))[,;\\)\\s\x08]')

def print_all_codes(text):
	for m in pattern.findall(text):
		print(m[0])
inside = False
for _ in range(int(input())):
	text = input()
	(left, right) = (0, len(text))
	if '{' in text:
		inside = True
		left = text.find('{')
	if '}' in text:
		inside = False
		right = text.find('}')
	if inside:
		print_all_codes(text[left:right])


n = int(input())
code = []
hexVals = []
searching = False
valid = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', '#']
for i in range(n):
	code += input().split()
for i in range(len(code)):
	if '{' in code[i]:
		searching = True
	if '}' in code[i]:
		searching = False
	if searching:
		if '#' in code[i]:
			hexVals.append(code[i])
for i in range(len(hexVals)):
	temp = ''
	searching = False
	for c in range(len(hexVals[i])):
		if hexVals[i][c] == '#':
			searching = True
		if not searching:
			continue
		if searching and hexVals[i][c] in valid:
			temp += hexVals[i][c]
		else:
			hexVals[i] = temp
			break
	if len(hexVals[i]) == 7 or len(hexVals[i]) == 4:
		print(hexVals[i])


import re
color = re.compile('(#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?)[\\(\\),;))]')
xml = []
for _ in range(int(input())):
	xml.append(input())
xml = ''.join(xml)
print(*color.findall(xml), sep='\n')


import re
import sys
rl = lambda : sys.stdin.readline()
pattern = '\\#([a-fA-F0-9]{3}(?![a-fA-F0-9])|[a-fA-F0-9]{6})'
t = int(rl())
txt = []
for _ in range(t):
	txt.append(rl().strip())
open = False
for s in txt:
	if '{' in s:
		open = True
		s = ''.join(s[s.index('{') + 1:])
	elif '}' in s:
		open = False
	if bool(open):
		p = re.finditer(pattern, s)
		for m in p:
			print(m.group())


lokal = 0
if lokal:
	f = open('in.txt')
	inFkt = f.readline
else:
	inFkt = input
import os, re
N = int(inFkt())
p = '#[a-fA-F0-9]{3}[^a-fA-F0-9]|#[a-fA-F0-9]{6}[^a-fA-F0-9]'
outside = 1
for n in range(0, N):
	txt = inFkt()
	if outside == 0:
		if re.match('.*}.*', txt):
			outside = 1
		else:
			hexs = re.findall(p, txt)
			for h in hexs:
				print(h[:-1])
	elif re.match('.*{.*', txt):
		outside = 0


import re
inside_css = False
for _ in range(int(input())):
	s = input()
	if not s:
		pass
	elif s[-1] == '{':
		inside_css = True
	elif s[-1] == '}':
		inside_css = False
	elif inside_css:
		for e in re.finditer('#[0-9a-fA-F]+', s):
			if len(e.group(0)) == 4 or len(e.group(0)) == 7:
				print(e.group(0))


__author__ = 'Shivani'
import re

def css(s):
	if len(s) > 0 and s[0] == '#':
		return
	p = re.compile('(#([0-9a-fA-F]){6})|(#([0-9a-fA-F]){3})')
	m = p.finditer(s)
	if m != None:
		for i in m:
			print(i.group())

def main():
	n = int(input())
	for i in range(n):
		css(input())
main()


import re
import sys

def extract(s):
	pattern = re.compile('(\\#[0-9a-fA-F]{6}|\\#[0-9a-fA-F]{3})')
	return pattern.findall(s)
n = int(sys.stdin.readline())
for nline in range(n):
	line = sys.stdin.readline()
	if line.find(':') < 0:
		continue
	for color in extract(line):
		print(color)


import re
n = int(input())
s = ''
for i in range(n):
	s += input() + '\n'
o = re.findall('(?i)(\\#([0-9a-f]{3,3}|[0-9a-f]{6,6})(?=(;|,|\\))))', s)
for i in o:
	print(i[0])


import re
inside = False
prog = re.compile('(\\#[0-9A-Fa-f]{3,6})')
for _ in range(int(input())):
	line = input()
	if not line:
		continue
	if '{' in line:
		line = line.split('{', 1)[1]
		inside = True
	if not inside:
		continue
	if '}' in line:
		line = line.split('}', 1)[0]
		inside = False
	for m in prog.finditer(line):
		string = m.group(1)
		if len(string) in (4, 7):
			print(string)


import fileinput

def checkHex(h):
	if len(h) < 4 or len(h) > 7:
		return False
	for x in h:
		if x.upper() not in ['#', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F']:
			return False
	return True
s = ''
for x in fileinput.input():
	s += str(x)
s = s.replace(' ', '')
t = s.rstrip()
t = t.split()
p = ''
for x in t:
	p += str(x)
toprint = []
inCurly = False
inHex = False
r = ''
for ch in p:
	if inCurly:
		if ch == '#':
			inHex = True
		if inHex:
			if ch.upper() not in ['#', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F']:
				inHex = False
				toprint.append(r)
				r = ''
			else:
				r += str(ch)
	if ch == '{':
		inCurly = True
	if ch == '}':
		inCurly = False
for x in toprint:
	if checkHex(x):
		print(x)


import re
import sys
inp = sys.stdin.read()
for i in re.findall('#(?:(?:[a-f]|[A-F]|\\d){3}){1,2}(?!\\s*{)', inp):
	print(i)


n = int(input())
hexa = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
l = []
for _ in range(n):
	s = input()
	if s.count(':') != 0:
		while s.count('#') != 0:
			s = s[s.index('#') + 1:]
			h = '#'
			for c in s:
				if c.lower() not in hexa:
					break
				h += c
			if len(h) == 4 or len(h) == 7:
				print(h)