使用Python正则表达式将SystemVerilog打包数组转为解包数组
Convert SystemVerilog Packed Arrays to Unpacked with Python Regex
Here's a practical, straightforward way to transform those packed array declarations into unpacked ones using Python's re module:
Step-by-Step Breakdown
First, let's map the pattern we're working with:
- Input line structure:
<direction> <[range]> <signal_name>; - Desired output:
<direction> <signal_name> <[range]>;
We'll use regex to capture the three key components (direction, range, signal name) and rearrange them into the new format.
Regex Pattern & Replacement
The regex below targets exactly the structure of your lines, accounting for minor whitespace variations:
pattern = r'^(\w+)\s+\[(\d+:\d+)\]\s+(\w+);$' replacement = r'\1 \3 [\2];'
^(\w+): Grabs the direction (inout/input/output) at the start of the line.\s+\[(\d+:\d+)\]\s+: Captures the numeric range inside brackets, ignoring any surrounding spaces.(\w+);$: Captures the signal name just before the closing semicolon.- The replacement string swaps the position of the signal name and range.
Full Python Code Example
import re # Load your input content (replace with file reading for real use) input_text = """inout [5:0] IO_PMU_LED; input [7:0] PMU_DI_SCAN_IN_VCORE; inout [31:0] PMU_DI_RIF_WR_DATA_VLP ; output [9:0] PMU_DI_RIF_ADDR_VLP; input [5:0] PMU_DI_LED_PAD_DRIVE_VALUE_VLP; output [5:0] PMU_DI_LED_PAD_DRIVE_ENABLE_VLP;""" # Process each line processed_lines = [] for line in input_text.splitlines(): # Clean up trailing whitespace first (handles the extra space in line 3) cleaned_line = line.rstrip() # Apply regex replacement if the line matches our pattern modified_line = re.sub(pattern, replacement, cleaned_line) processed_lines.append(modified_line) # Combine lines back into a single string output_text = '\n'.join(processed_lines) # Print result or write to file print(output_text)
Result
Running this code will produce exactly the output you want:
inout IO_PMU_LED [5:0]; input PMU_DI_SCAN_IN_VCORE [7:0]; inout PMU_DI_RIF_WR_DATA_VLP [31:0]; output PMU_DI_RIF_ADDR_VLP [9:0]; input PMU_DI_LED_PAD_DRIVE_VALUE_VLP [5:0]; output PMU_DI_LED_PAD_DRIVE_ENABLE_VLP [5:0];
Bonus: File I/O
To use this on a real file instead of sample text, replace the input/output sections with:
# Read from input file with open('your_input_file.sv', 'r') as f: input_text = f.read() # Write to output file with open('your_output_file.sv', 'w') as f: f.write(output_text)
内容的提问来源于stack exchange,提问作者sanforyou
相关产品推荐
相关产品推荐

