0

Problem: I have to find valid hex colours in a file, but not to include any selectors that potentially might conflict with it.

For example, in the below code,

#Cab
{
    background-color: #ABC;
    border: 2px dashed #fff;
} 

#ABC and #fff are valid, but not #cab .

Question: Is it possible to put condition for substring before and after the intended string of search. Here, i need this #[0-9a-fA-F]{3,3}|#[0-9a-fA-F]{6,6} to be searched. But only if the substring immediately before it is :[\w\s]* and substring immediately after it is \W

Note 1: I figured that searching for \W after the string can be be done by adding \b in the original search.

Note 2: This was a problem in python, and I could trim it through python, but wondering if there is a way to do this through regex.

1 Answers1

2

Try

#! /usr/bin/env python3

import re
string = """
#Cab
{
    background-color: #ABC;
    border: 2px dashed #fff;
    border:         2px dashed #ffe;
    border:         2px     #123;
    color:#ff00ff;
    color: #FfFdF8; background-color:#aef;
}
"""

pattern = re.compile(r':\s*[\w\s]*(#[0-9A-F]{3}|#[0-9A-F]{6});', flags=re.IGNORECASE)
match = re.findall(pattern, string)  # where 'string' is your input

print(match)

which produces

['#ABC', '#fff', '#ffe', '#123', '#ff00ff', '#FfFdF8', '#aef']
JRiggles
  • 4,847
  • 1
  • 12
  • 27
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • thank you both.. solves my question with usage of `()`. I modified pattern `:[\w\s\-,\(\)\#]*(#[0-9a-fA-F]{3}|#[0-9a-fA-F]{6})[\(\)\,\s\-]?[;|,]` to account for extreme cases for eg, colour gradient where multiple colours are separated by commas and inside a bracket. Still it failed in cases where 2 colours were there in a single group (one match per group). To find multiple matches in single group I used this https://stackoverflow.com/questions/37003623/how-to-capture-multiple-repeated-groups – Parthiban Bala Jan 04 '23 at 19:50