如何用Python正则或文本替换简化PL/1代码中的多条件IF语句?
Simplifying Verbose PL/1 IF Conditions with Python
Absolutely! I’ve tackled similar PL/1 code cleanup tasks before, and Python’s regex and string processing tools are perfect for automating this kind of repetitive simplification. Here’s a practical, tested solution to turn those clunky OR’d conditions into clean in() checks:
Step-by-Step Solution
First, we’ll use a combination of regex matching and a custom callback function to group conditions by variable, then rewrite them in the var in ('val1','val2') format.
Python Code Implementation
import re def simplify_pl1_if(match): # Extract the core conditions from the IF statement raw_conditions = match.group(1) # Split conditions by the OR operator, stripping extra whitespace condition_parts = [part.strip() for part in raw_conditions.split('|')] # Group conditions by their variable name variable_groups = {} unprocessed_conditions = [] for cond in condition_parts: # Match patterns like "cond == 'A'" or "cond_ex=='B_EX'" var_value_match = re.match(r'(\w+)\s*==\s*\'([^\']+)\'', cond) if var_value_match: var_name = var_value_match.group(1) value = var_value_match.group(2) # Build a list of values for each variable if var_name not in variable_groups: variable_groups[var_name] = [] variable_groups[var_name].append(value) else: # Keep any non-matching conditions (e.g., cond > 10) as-is unprocessed_conditions.append(cond) # Construct the simplified condition parts simplified_segments = [] for var, values in variable_groups.items(): joined_values = "','".join(values) simplified_segments.append(f"{var} in ('{joined_values}')") # Add back any unprocessed conditions simplified_segments.extend(unprocessed_conditions) # Reassemble the full IF statement return f"if {' | '.join(simplified_segments)} then;" # Test with your example original_line = "if cond == 'A' | cond == 'B' | cond == 'C' | cond_ex == 'A_EX' | cond == 'D' | cond_ex == 'B_EX' then;" simplified_line = re.sub(r'if\s+(.*?)\s+then;', simplify_pl1_if, original_line) print(simplified_line) # Output: if cond in ('A','B','C','D') | cond_ex in ('A_EX','B_EX') then;
How It Works
- Regex Matching: The outer
re.subtargets the entire IF statement, capturing everything betweenifandthen;for processing. - Condition Splitting: We split the captured conditions using
|as the delimiter, cleaning up extra whitespace along the way. - Grouping by Variable: For each condition, we check if it follows the
var == 'value'pattern. If so, we group all values under their corresponding variable. - Simplification: We convert each variable’s value list into a single
var in ('val1','val2')expression. - Handling Edge Cases: Any conditions that don’t fit the pattern (like numeric comparisons or complex expressions) are preserved in their original form.
Batch Processing PL/1 Files
To apply this to an entire PL/1 source file, just read the file line by line, process each line, and write the output to a new file:
with open("old_source.pl1", "r") as infile, open("clean_source.pl1", "w") as outfile: for line in infile: # Apply the simplification to lines containing IF statements processed_line = re.sub(r'if\s+(.*?)\s+then;', simplify_pl1_if, line) outfile.write(processed_line)
Notes for Adjustments
- Quotation Marks: If your PL/1 code uses double quotes instead of single quotes, modify the regex to use
"instead of'. - Logical ANDs: If you need to handle
&operators too, you’ll need to adjust the splitting logic (this solution focuses on|as per your example). - Case Sensitivity: PL/1 is case-insensitive for keywords, but variables are case-sensitive. The regex respects variable case as written.
内容的提问来源于stack exchange,提问作者Tae Young Lee
相关产品推荐
相关产品推荐

