1

I am trying to check a string for a pattern which its length can be either 3 or 6; not the values between them.

This is the string:

color: #FfFdF8; background-color:#aef;

I want to get all sub-strings starting with # followed by a hex code, if they have the length of 3 or 6 and are not located at the beginning of the string; in this case both #FfFdF8 and #aef should be returned.

I have written this pattern:

r'^(?!#).+(#[a-fA-F0-9]{6}).*|^(?!#).+(#[a-fA-F0-9]{3}).*'

But it gave me [('#FfFdF8', '')] as the result of re.findall.

2
  • 1
    if not s.startswith('#'): results = re.findall(r'#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?\b', s) Commented Oct 12, 2019 at 7:17
  • @WiktorStribiżew, it worked. Thanks. Would you please post it as an answer? Commented Oct 12, 2019 at 7:37

1 Answer 1

1

You may first check if the string starts with # and if not, extract the #... substrings:

import re
results = []
s = 'color: #FfFdF8; background-color:#aef;'
if not s.startswith('#'): 
    results = re.findall(r'#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?\b', s)
print(results) # => ['#FfFdF8', '#aef']

See the regex demo and the Python demo.

Regex details

  • # - a # char
  • [a-fA-F0-9]{3} - 3 hex chars
  • (?:[a-fA-F0-9]{3})? - an optional sequence of three hex chars
  • \b - a word boundary (no more hex chars to the right are allowed)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.