To parse stylesheets and extract information about @font-face declarations using regex in Python, we can create a function that processes the CSS text. The function will:
- Remove CSS comments to avoid interference with parsing.
- Identify all
@font-face blocks using regex.
- Extract key-value pairs (e.g.,
font-family, src, font-weight, font-style) from each block using regex.
- Return a list of dictionaries, where each dictionary represents a font-face declaration with its properties.
Here's a Python code snippet that implements this:
import re
def parse_font_faces(css_text):
# Step 1: Remove CSS comments using regex
css_text_no_comments = re.sub(r'/\*.*?\*/', '', css_text, flags=re.DOTALL)
# Step 2: Find all @font-face blocks using regex
# Pattern: @font-face followed by optional whitespace, an opening brace,
# and capture the content until the closing brace (non-greedy, allow newlines)
font_face_pattern = r'@font-face\s*\{(.*?)\}'
font_face_blocks = re.findall(font_face_pattern, css_text_no_comments, flags=re.DOTALL)
# Step 3: Parse each @font-face block and extract properties
result = []
for block in font_face_blocks:
# Pattern for properties: key (e.g., font-family) followed by optional whitespace,
# a colon, optional whitespace, and the value until a semicolon or end (non-semicolon characters)
property_pattern = r'([\w-]+)\s*:\s*([^;]+)'
properties_matches = re.findall(property_pattern, block)
# Convert matches to a dictionary and strip whitespace from values
prop_dict = {key: value.strip() for key, value in properties_matches}
# Add the dictionary to the result list
result.append(prop_dict)
return result
# Example usage
css_example = '''
/* This is a sample CSS stylesheet with comments */
@font-face {
font-family: 'CustomFont';
src: url('customfont.woff2') format('woff2');
font-weight: normal;
font-style: italic;
}
@font-face {
font-family: 'AnotherFont';
src: url('anotherfont.ttf') format('truetype');
font-weight: bold;
}
'''
font_faces = parse_font_faces(css_example)
for font_face in font_faces:
print(font_face)
Explanation of the Code:
- Regex for Comments Removal:
r'/\*.*?\*/' with re.DOTALL flag matches and removes block comments (e.g., /* comment */) from the CSS text. This ensures comments don't interfere with property parsing.
- Regex for @font-face Blocks:
r'@font-face\s*\{(.*?)\}' with re.DOTALL finds all @font-face declarations. The \s* handles optional whitespace, and (.*?) (non-greedy) captures the content inside the braces, allowing for multi-line blocks.
- Regex for Properties:
r'([\w-]+)\s*:\s*([^;]+)' extracts key-value pairs within each block.
([\w-]+) captures the property name (e.g., font-family), allowing word characters and hyphens.
\s*:\s* matches the colon with optional surrounding whitespace.
([^;]+) captures the value until a semicolon or the end of the string.
- Post-Processing: After extracting matches, the values are stripped of leading/trailing whitespace using
value.strip() to clean up the output.
- Output: The function returns a list of dictionaries. Each dictionary contains the properties of a single
@font-face declaration.
Example Output for the Provided CSS:
For the css_example input, the output would be:
{'font-family': 'CustomFont', 'src': "url('customfont.woff2') format('woff2')", 'font-weight': 'normal', 'font-style': 'italic'}
{'font-family': 'AnotherFont', 'src': "url('anotherfont.ttf') format('truetype')", 'font-weight': 'bold'}
Limitations:
- This implementation assumes relatively well-formed CSS. It may not handle:
- Malformed CSS (e.g., missing semicolons between properties).
- Complex values with embedded semicolons (though rare in
@font-face).
- Other CSS features like nested rules or vendor-specific syntax.
- If you need more robust parsing (e.g., handling all edge cases), consider using a dedicated CSS parser library like
cssutils or tinycss2 in Python, as regex alone can struggle with the full complexity of CSS.
This approach uses regex as requested and should work for most standard @font-face declarations in stylesheets. If you have specific CSS examples or additional requirements, I can refine this further!