Reputation: 120
I'm trying to create a regex to catch all hexadecimal colors in a string literal. I'm using Python 3, and that's what I have:
import re
pattern = re.compile(r"#[a-fA-F\d]{3}([a-fA-F\d]{3})?")
However, when I apply the findall
regex method on #abcdef
here's what I get:
>>> re.findall(pattern,"#abcdef")
["def"]
Can someone explain me why do I have that? I actually need to get ["#abcdef"]
Thank you in advance
Upvotes: 0
Views: 65
Reputation: 120
Thanks to Andrej Kesely, I got the answer to my question, that is:
Regex will return capturing group.
To bypass this, just change the regex from:
r"#[a-fA-F\d]{3}([a-fA-F\d]{3})?"
to:
r"#[a-fA-F\d]{3}(?:[a-fA-F\d]{3})?"
Upvotes: 1
Reputation: 71
According to http://regex101.com:
It looks like this regex is looking for
#(three characters a through f, A through F or a digit)(three characters a through f, A through F or a digit, which may or may not be present, and if they are they are what is returned from the match)
If you are looking to match any instance of the whole above string, I would recommend this instead:
Upvotes: 1