Okay, let's use Python's re module to parse CSS stylesheets and extract font-family declarations.
Understanding the font-family Property
The font-family CSS property specifies the font for an element. It can accept a list of font names (families) as a fallback sequence. Font names might be:
Unquoted: Simple names like Arial, Verdana, serif.
Quoted: Names with spaces or special characters, enclosed in single (') or double (") quotes, like "Times New Roman", 'Courier New'.
Generic Families: Keywords like sans-serif, serif, monospace, cursive, fantasy, system-ui.
The declarations are typically structured like: font-family: value1, value2, value3;
Python Regex Approach
We need a regex that can find the font-family property, capture its value, and handle potential variations in spacing and quoting. We'll capture the entire value string and then process it in Python to get individual font names.
python
import re
def extract_font_families(css_string):
"""
Extracts font-family declarations from a CSS string using regex.
Args:
css_string: A string containing CSS rules.
Returns:
A list of lists. Each inner list contains the font names
(cleaned of quotes and surrounding whitespace) for a single
font-family declaration found in the CSS.
Returns an empty list if no font-family declarations are found.
"""
# Regex explanation:
# font-family\s*:\s* : Matches "font-family" property name, colon, and any surrounding whitespace.
# Case-insensitive due to re.IGNORECASE flag.
# ( : Start capturing group 1 (this is what findall returns)
# (?: : Start a non-capturing group (to group parts of the value)
# "[^"]*" : Matches a double-quoted string (non-greedy)
# | : OR
# '[^']*' : Matches a single-quoted string (non-greedy)
# | : OR
# [^;{}]+ : Matches one or more characters that are NOT a semicolon,
# opening brace, or closing brace (handles unquoted names and generic families)
# ) : End the non-capturing group
# (?: : Start a non-capturing group for comma-separated sequences
# \s*,\s* : Matches a comma potentially surrounded by whitespace
# (?: : Start a non-capturing group for the next font name part
# "[^"]*" | '[^']*' | [^;{}]+
# )* : Match zero or more subsequent font names (handles the rest of the list)
# )? : Make the entire comma-separated part optional (for single-entry values)
# ) : End capturing group 1
# The regex tries to capture individual font names more directly.
# A simpler, often sufficient regex captures the whole value: r"font-family\s*:\s*([^;}]+)"
# Let's stick to the simpler one for robustness in parsing the value afterwards.
# Simpler Regex: Captures the entire value string until ';' or '}'
# Allows for easier post-processing in Python.
# Use re.IGNORECASE for case-insensitivity (e.g., "Font-Family")
# Use re.DOTALL in case the value spans multiple lines (less common for font-family)
pattern = r"font-family\s*:\s*([^;}]+)"
matches = re.findall(pattern, css_string, re.IGNORECASE | re.DOTALL)
all_fonts_parsed = []
for value_str in matches:
# Clean leading/trailing whitespace from the entire captured value
value_str = value_str.strip()
if not value_str:
continue # Skip if the value is empty after stripping
# Split the value string into individual font candidates by comma
font_candidates = value_str.split(',')
cleaned_fonts_in_declaration = []
for font in font_candidates:
# Clean leading/trailing whitespace from each candidate
cleaned_font = font.strip()
# Remove surrounding quotes (single or double) if they exist
if (cleaned_font.startswith('"') and cleaned_font.endswith('"')) or \
(cleaned_font.startswith("'") and cleaned_font.endswith("'")):
# Slice off the quotes and strip again in case of space like "' Font '"
cleaned_font = cleaned_font[1:-1].strip()
# Add the finally cleaned font name if it's not empty
if cleaned_font:
cleaned_fonts_in_declaration.append(cleaned_font)
# Add the list of cleaned fonts for this declaration if it's not empty
if cleaned_fonts_in_declaration:
all_fonts_parsed.append(cleaned_fonts_in_declaration)
return all_fonts_parsed
# --- Example Usage ---
css_example = """
/* Some CSS */
body {
font-family: Arial, Helvetica, sans-serif; /* Standard fonts */
margin: 0;
padding: 1em;
}
h1, h2 {
font-family: "Times New Roman", Times, serif; /* Serif fonts */
color: navy;
}
.special-text {
font-family: 'Courier New', Courier, monospace;
font-size: 14px;
}
.icon-font {
font-family: "icomoon", "FontAwesome", sans-serif;
}
/* Test cases */
.empty {
font-family: ; /* Empty */
}
.spacey {
font-family: Arial , "DejaVu Sans" ;
}
.no-semicolon {
font-family: Verdana
}
/* Another rule */
div {
font-family: cursive, fantasy, "Comic Sans MS"; color: green;
}
"""
extracted_families = extract_font_families(css_example)
print("Extracted Font Families:")
for fonts in extracted_families:
print(f"- {fonts}")
# --- Example Output ---
# Extracted Font Families:
# - ['Arial', 'Helvetica', 'sans-serif']
# - ['Times New Roman', 'Times', 'serif']
# - ["Courier New", "Courier", "monospace"]
# - ['icomoon', 'FontAwesome', 'sans-serif']
# - ['Verdana']
# - ['cursive', 'fantasy', 'Comic Sans MS']
Explanation:
Import re: Imports the regular expression module.
Define extract_font_families: Creates a function that accepts the CSS string.
Regex Pattern:r"font-family\s*:\s*([^;}]+)"
font-family: Matches the literal property name.
\s*:\s*: Matches the colon separator, allowing for zero or more whitespace characters around it.
([^;}]+): This is the main capturing group.
[^;}...]: Matches any character except a semicolon (;) or a closing curly brace (}). This effectively captures the value of the property.
+: Matches one or more of the preceding characters.
re.findall: This function finds all non-overlapping matches of the pattern in the string and returns a list of all captured groups. Since our pattern has one capturing group (...), it returns a list of the values found for font-family.
Flags:
re.IGNORECASE: Makes the pattern match font-family, Font-Family, FONT-FAMILY, etc.
re.DOTALL: Allows the . character in regex to match newline characters. This is useful if a font-family value happens to span across multiple lines, although less common.
Post-Processing:
The code iterates through each captured value_str.
It strip()s whitespace from the beginning and end of the whole value string.
It split(',') the value string to get a list of individual font candidates.
It iterates through these candidates, strip()s whitespace from each one.
It checks if the cleaned candidate is enclosed in quotes (" or ') and removes them if found, stripping again in case of spaces like "' Times '".
Non-empty, cleaned font names are added to cleaned_fonts_in_declaration.
The list for the current declaration (cleaned_fonts_in_declaration) is added to the final all_fonts_parsed list.
Return Value: The function returns the list, containing lists of cleaned font names.
Limitations:
Regex is Fragile: This regex-based approach works for well-formed CSS but can break easily with slightly malformed CSS, comments containing font-family: or semicolons/braces, or complex syntax variations.
Shorthand Properties: This specifically targets the font-family property. It won't extract fonts specified using the shorthand font property (e.g., font: italic bold 16px Arial, sans-serif;).
Context: It doesn't understand CSS structure (like selectors, nested rules) beyond finding the property itself.
Production Use: For robust CSS parsing in production applications, using a dedicated CSS parsing library (like cssutils, tinycss2, or cssselect) is highly recommended. They handle the complexities and edge cases of the CSS syntax much more reliably.