Zeinab Abbasimazar
Zeinab Abbasimazar

Reputation: 10449

Python regex checking length of the string for two discrete values

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.

Upvotes: 1

Views: 168

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

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)

Upvotes: 1

Related Questions