Skip to content
The Chat Archive
deepseek-v3-0324· DeepSeek LMArena Human Preference 140K

Use regex in python to parse stylesheets and return information regarding font-families…

  1. User

    Use regex in python to parse stylesheets and return information regarding font-families declared

  2. Assistant

    Parsing CSS Stylesheets for Font-Families with Python Regex

    Here's a Python solution using regular expressions to extract font-family declarations from CSS stylesheets:

    import re
    from typing import List, Dict, Union
    
    def extract_font_families(css_content: str) -> Dict[str, List[str]]:
        """
        Extract font-family declarations from CSS content.
        
        Args:
            css_content: String containing CSS stylesheet content
            
        Returns:
            Dictionary with selectors as keys and lists of font families as values
        """
        # Pattern to match CSS rules with font-family declarations
        pattern = r"""
            ([^{]+)                # Capture selector(s) before {
            \{                     # Opening brace
            [^}]*                  # Any content except closing brace
            font-family\s*:\s*     # font-family property
            ([^;]+)                # Capture font-family value
            [^}]*                  # Any remaining content before }
            \}                     # Closing brace
        """
        
        font_families = {}
        
        for match in re.finditer(pattern, css_content, re.VERBOSE | re.IGNORECASE):
            selectors = match.group(1).strip()
            families = match.group(2).strip()
            
            # Clean up the font-family values
            families = re.sub(r'["\']', '', families)  # Remove quotes
            families = [f.strip() for f in families.split(',')]  # Split multiple fonts
            families = [f for f in families if f]  # Remove empty strings
            
            if families:
                font_families[selectors] = families
                
        return font_families
    
    # Example usage
    if __name__ == "__main__":
        css = """
        body {
            font-family: "Helvetica Neue", Arial, sans-serif;
            color: #333;
        }
        
        h1, h2 {
            font-family: Georgia, serif;
            font-weight: bold;
        }
        
        .special {
            font-FAMILY: 'Comic Sans MS', cursive;
            background: yellow;
        }
        """
        
        result = extract_font_families(css)
        for selector, families in result.items():
            print(f"{selector}: {', '.join(families)}")
    

    How It Works:

    1. The regex pattern matches:

      • CSS selectors (before the opening brace)
      • The font-family property declaration
      • The font family values (including multiple fonts separated by commas)
    2. The function:

      • Handles both single and multiple font declarations
      • Removes quotes around font names
      • Splits comma-separated font families
      • Is case-insensitive (matches font-family, FONT-FAMILY, etc.)
      • Returns a dictionary with selectors as keys and font lists as values

    Example Output:

    For the sample CSS above, the output would be:

    body: Helvetica Neue, Arial, sans-serif
    h1, h2: Georgia, serif
    .special: Comic Sans MS, cursive
    

    Advanced Version (Handling @font-face):

    If you also want to extract font families defined in @font-face rules:

    def extract_all_fonts(css_content: str) -> Dict[str, Union[List[str], Dict[str, str]]]:
        """
        Extract all font-family declarations including @font-face rules.
        
        Returns:
            Dictionary with two keys:
            - 'selectors': Regular CSS rule font families
            - 'font_faces': @font-face rule font families with src if available
        """
        result = {
            'selectors': {},
            'font_faces': []
        }
        
        # Extract regular CSS rule font families
        result['selectors'] = extract_font_families(css_content)
        
        # Extract @font-face rules
        font_face_pattern = r"""
            @font-face\s*          # @font-face at-rule
            \{                     # Opening brace
            ([^}]*)                # All content inside
            \}                     # Closing brace
        """
        
        font_decl_pattern = r"""
            font-family\s*:\s*     # font-family property
            ([^;]+)                # Capture value
        """
        
        src_pattern = r"""
            src\s*:\s*             # src property
            ([^;]+)                # Capture value
        """
        
        for match in re.finditer(font_face_pattern, css_content, re.VERBOSE | re.IGNORECASE):
            font_face_content = match.group(1)
            
            font_match = re.search(font_decl_pattern, font_face_content, re.VERBOSE | re.IGNORECASE)
            src_match = re.search(src_pattern, font_face_content, re.VERBOSE | re.IGNORECASE)
            
            if font_match:
                font_family = font_match.group(1).strip()
                font_family = re.sub(r'["\']', '', font_family)
                src = src_match.group(1).strip() if src_match else None
                
                result['font_faces'].append({
                    'font-family': font_family,
                    'src': src
                })
        
        return result
    

    This enhanced version will also capture web fonts defined in @font-face rules along with their source URLs.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.