python-regexHow to match a hex color with regex in Python?
Regex can be used to match a hex color in Python. The regex pattern for a hex color is #[A-Fa-f0-9]{6}
. This pattern will match any valid hex color code, including the # symbol.
Example code
import re
hex_color_regex = re.compile(r'#[A-Fa-f0-9]{6}')
hex_color = '#FF0000'
if hex_color_regex.match(hex_color):
print('Valid hex color')
else:
print('Invalid hex color')
Output example
Valid hex color
Code explanation
import re
: imports there
module which contains there.compile()
function used to create the regex pattern.hex_color_regex = re.compile(r'#[A-Fa-f0-9]{6}')
: creates a regex pattern object using there.compile()
function. The pattern#[A-Fa-f0-9]{6}
will match any valid hex color code, including the # symbol.hex_color = '#FF0000'
: sets the variablehex_color
to a valid hex color code.if hex_color_regex.match(hex_color):
: checks if thehex_color
variable matches the regex pattern.print('Valid hex color')
: prints the messageValid hex color
if thehex_color
variable matches the regex pattern.print('Invalid hex color')
: prints the messageInvalid hex color
if thehex_color
variable does not match the regex pattern.
Helpful links
More of Python Regex
- How to replace all using Python regex?
- How to count matches with Python regex?
- How to match a year with Python Regex?
- How to perform a zero length match with Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to match a hex number with regex in Python?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
See more codes...